如何使用VBA函数计算Excel中的非数字字数

Ada*_*les 2 string excel vba function

例如,我想要一个字符串,例如,"这是一个单词组中的13个可能的1个单词,来自字典或BookZZ或者Libgen.io 1876"给我一个19的结果(因为"13" ,"1876"和"1"是数字,不应计算在内.

我创建了两个函数,我试图在这个函数中使用我要问的:

第一个是以下内容:

' NthWord prints out the Nth Word of a String of Text in an Excel Cell such 
' as A1 or B19.

Function NthWord(ActiveCell As String, N As Integer)

Dim X As String
X = ActiveCell

X = Trim(Mid(Replace(ActiveCell, " ", Application.WorksheetFunction.Rept(" 
", Len(ActiveCell))), (N - 1) * Len(ActiveCell) + 1, Len(ActiveCell)))

NthWord = X

' In the Excel SpreadSheet:
' Trim (Mid(Substitute(A1, " ", Rept(" ", Len(A1))), (N - 1) * Len(A1) 
' + 1, Len(A1)))

End Function 
Run Code Online (Sandbox Code Playgroud)

第二个是以下内容:

'NumberOfWords returns the number of words in a String 

Function NumberOfWords(ActiveCell As String)

Dim X As String
X = ActiveCell
Dim i As Integer
i = 0

If Len(Trim(X)) = 0 Then
    i = 0
Else:
    i = Len(Trim(X)) - Len(Replace(X, " ", "")) + 1
End If

NumberOfWords = i


' In the Excel SpreadSheet
' IF(LEN(TRIM(A1))=0,0,LEN(TRIM(A1))-LEN(SUBSTITUTE(A1," ",""))+1)


End Function
Run Code Online (Sandbox Code Playgroud)

我尝试打印NumberOfNonNumberWords

Function NumberOfNonNumberWords(ActiveCell As String)

Dim X As String
X = ActiveCell
Dim count As Integer
count = 0
Dim i As Integer

If NumberOfWords(X) > 0 Then
    For i = 1 To NumberOfWords(X)

        If Not (IsNumeric(NthWord(X, i).Value)) Then
            count = count + 1
        End If

    Next i
End If


NumberOfNonNumberWords = count

End Function
Run Code Online (Sandbox Code Playgroud)

但是,当我在Excel工作表中应用此函数时,我得到一个输出, #VALUE! 我不知道为什么.我该如何解决?

小智 5

拆分整个字符串然后计算非数字元素.

function abcWords(str as string) as long

    dim i as long, arr as variant

    arr = split(str, chr(32))

    for i=lbound(arr) to ubound(arr)
        abcWords = abcWords - int(not isnumeric(arr(i)))
    next i

end function
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 在VBA中,*True*在数字上减去1,而不是像在工作表上那样. (3认同)
  • `abcWords = abcWords - int()`如何工作?`int()`会返回一个`1`,或'0`正确吗?当你没有首先将'abcWords`声明为某种东西时,如何从它自身中减去它? (2认同)
  • @BruceWayne,与任何未声明的var一样,未声明的函数是默认情况下以数字方式实例化为零的变体,因此如果您开始在变量中添加或减去数字,则最终会得到数字. (2认同)