Excel

Cómo contar el número de caracteres en una cadena

¿Alguna vez necesitaste obtener el número de caracteres de una cadena?

¡Es muy fácil! Simplemente use la función Len().

lLength = Len("My string to get the character count of.")

Pero ¿qué sucede si desea contar los caracteres pero ignora uno o más caracteres? ¿Qué sucede si no desea contar los “espacios” o, tal vez, los signos de puntuación?

¿Que haces entonces?

¡La solución es muy sencilla como se demuestra en los ejemplos de código a continuación!

Exclusión de caracteres individuales

'---------------------------------------------------------------------------------------
' Procedure : CharCount
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : 
' Purpose   : Count the number of characters in a string
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - 
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput                    : String to count the number of characters within it
' sCharsToExcludeFromCount  : A list of characters to not include in the count
'
' Usage:
' ~~~~~~
' ? CharCount("   A word is just text surrounded by whitespace .  ")
'   Returns -> 51
'
' ? CharCount("   A word is just text surrounded by whitespace .  ", " .!?")
'   Returns -> 37
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-03-23              Initial Release
'---------------------------------------------------------------------------------------
Public Function CharCount(ByVal sInput As String, _
                          Optional ByVal sCharsToExcludeFromCount As String) As Long
    On Error GoTo Error_Handler
    Dim lCounter              As Long

    'Remove any excluded characters
    If sCharsToExcludeFromCount  "" Then
        For lCounter = 1 To Len(sCharsToExcludeFromCount)
            sInput = Replace(sInput, Mid(sCharsToExcludeFromCount, lCounter, 1), "")
        Next lCounter
    End If
    'Get the character count
    CharCount = Len(sInput)

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: CharCount" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl  0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Como puede ver, esta función toma 2 argumentos: la cadena para obtener el recuento de caracteres y una lista de caracteres que NO se incluirán en el recuento.

Básicamente, la función comenzará eliminando los caracteres especificados que NO se incluirán en el recuento y luego realizará la verificación Len().

Si desea la longitud completa, omita el segundo argumento. De lo contrario, simplemente pase como segundo argumento una cadena de caracteres que NO se incluirán en el recuento.

Exclusiones de múltiples caracteres/patrones

El ejemplo anterior es excelente si desea excluir caracteres individuales, pero ¿qué sucede si desea excluir patrones, una serie de caracteres específicos? Bueno, entonces podría usar una función como:

'---------------------------------------------------------------------------------------
' Procedure : CharCount
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : 
' Purpose   : Count the number of characters in a string
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - 
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput                    : String to count the number of characters within it
' sCharsToExcludeFromCount  : A list of characters to not include in the count
'
' Usage:
' ~~~~~~
' ? CharCount("   A word is just text surrounded by whitespace .  ")
'   Returns -> 51
'
' ? CharCount("   A word is just text surrounded by whitespace .  ", " ,.,!,?")
'   Returns -> 37
'
' ? CharCount("   A word is just text s, surrounded by whitespace .  ", " |.|!|?|,", "|")
'   Returns -> 38
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-03-23              Initial Release
'---------------------------------------------------------------------------------------
Public Function CharCount(ByVal sInput As String, _
                          Optional ByVal sCharsToExcludeFromCount As String, _
                          Optional ByVal sDelimiter As String = ",") As Long
    On Error GoTo Error_Handler
    Dim lCounter              As Long
    Dim aExclusions()         As String

    'Remove any excluded characters
    If sCharsToExcludeFromCount  "" Then
        aExclusions = Split(sCharsToExcludeFromCount, sDelimiter)
        For lCounter = 0 To UBound(aExclusions)
            sInput = Replace(sInput, aExclusions(lCounter), "")
        Next lCounter
    End If
    'Get the character count
    CharCount = Len(sInput)

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: CharCount" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl  0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Esta función acepta 3 argumentos de entrada: la cadena de la cual se obtendrá el recuento de caracteres, una lista delimitada de caracteres/patrones que NO se incluirán en el recuento y el delimitador utilizado en el segundo argumento (para usar para dividir los caracteres/patrones).

Bueno ahí lo tienes, tres formas sencillas de obtener el recuento de caracteres de una cadena:

  • Para casos simples, utilice la función Len()
  • Cuando necesite omitir caracteres individuales del recuento, utilice la primera función CharCount()
  • Cuando necesite omitir caracteres y/o patrones individuales del recuento, utilice la segunda función CharCount()

¿Qué pasa con la automatización de palabras?

Investigué el uso de la automatización de Word para obtener el recuento de caracteres e incluso desarrollé un par de funciones diferentes, como:

'---------------------------------------------------------------------------------------
' Procedure : Word_CharCount
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : 
' Purpose   : Count the number of characters in a string using Word automation
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - 
' Req'd Refs: Late Binding  -> None required
'             Early Binding -> Microsoft Word XX.X Object Library
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput                    : String to count the number of characters within it
'
' Usage:
' ~~~~~~
' ? Word_CharCount("   A word is just text surrounded by whitespace .  ")
'   Returns -> 51
'
' ? Word_CharCount("A word is just text" & vbnewline & " surrounded by whitespace .")
'   Returns -> 47   !!!Wrong!!! should be 46 - counting vbnewline as a character?!
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-03-23              Initial Release
'---------------------------------------------------------------------------------------
Public Function Word_CharCount(ByVal sInput As String)
On Error GoTo Error_Handler
    #Const Word_EarlyBind = False    'True => Early Binding / False => Late Binding
                                     'Microsoft Word XX.X Object Library
    #If Word_EarlyBind = True Then
        Dim oWord             As Word.Application
        Dim oDoc              As Word.Document

        Set oWord = New Word.Application
    #Else
        Dim oWord             As Object
        Dim oDoc              As Object
        Const wdStatisticCharacters = 3

        Set oWord = CreateObject("Word.Application")
    #End If

    oWord.Visible = False
    Set oDoc = oWord.Documents.Add
    oDoc.Activate
    oWord.Selection.TypeText sInput
    oWord.Selection.WholeStory

    'Both are inaccurate!
    Word_CharCount = oDoc.Characters.Count - 1

Error_Handler_Exit:
    On Error Resume Next
    oWord.Quit False
    Set oWord = Nothing
    Exit Function

Error_Handler:
    oWord.Visible = True
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: Word_CharCount" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl  0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

También intenté usar:

Word_CharCount = oDoc.ComputeStatistics(wdStatisticCharacters) 'omits spaces?!

Ambos enfoques presentan problemas/errores u omiten espacios en su recuento, lo que da como resultado un recuento incorrecto en ciertos casos.

No estoy seguro de qué tenía Microsoft en su ingenio cuando codificó estas cosas, pero vaya, ¡debe haber sido algo bueno!

En pocas palabras, si desea obtener el valor de recuento de palabras, puede usar lo anterior bajo su propio riesgo, pero si realmente desea un recuento válido y preciso, evite la automatización de Word por completo y quédese con uno de los otros enfoques mencionados anteriormente.

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba