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

时间:2018-10-26 18:47:02

标签: excel vba string function

例如, 我想要一个字符串,例如“这是一堆单词,它包含来自Dictionary,BookZZ或Libgen.io 1876的13个可能的1个单词”,结果为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 

第二个是以下内容:

'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

我尝试打印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

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

2 个答案:

答案 0 :(得分:5)

分割整个字符串,然后计算非数字元素。

function zeroCount(n) {
  let fives = 0;
  let twos = 0;
  for (let counter = 2; counter <= n; counter++) {
    let n = counter;
    while (n % 2 === 0) {
      n /= 2;
      twos++;
    }
    while (n % 5 === 0) {
      n /= 5;
      fives++;
    }
  }
  return Math.min(fives, twos);
}
console.log(zeroCount(6)); // 720
console.log(zeroCount(10)); // 3628800

enter image description here

答案 1 :(得分:4)

您可以只使用methodTether.invoke()在空格分隔符上分割文本,然后计算非数字单词:

SPLIT()