Excel VBA – 长格式文字分析的两大挑战

我希望能够做到以下两点: 我知道Excel公式,但我希望有一种方法来编程这个瓦特/ VBA。

  1. 我使用Excel公式为列B中的输出执行每个单元格的字数:

= LEN(TRIM($ A2)) – LEN(SUBSTITUTE($ A2,“”,“”))+ 1

A列中的单元格包含自由格式的文本,范围从500到2500个单词,并且分隔符是空格。 包含文本的单元格的数量因工作簿而异。

到目前为止,我已经尝试input下面的代码,没有运气。 我收到types不匹配

码:

Dim lastRow As Long With Sheets("Sheet1") lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row With .Range("B2:B" & lastRow).Formula = "=IF(LEN(TRIM(A2))=0,0,LEN(TRIM(A1))-LEN(SUBSTITUTE(A2,"" "",""""))+1)" .Value = .Value End With End With 
  1. 我试图做的第二步是search列标题(列C到BZ),并计算该单词出现在每个单元格中的次数。

=(LEN($ A2)-LEN(SUBSTITUTE(UPPER($ A2),UPPER(C $ 2), “”)))/ LEN(C $ 1)

不像上面的问题,我一直无法启动一个脚本。

一个VBAmacros可能会为此目的执行得最快。 这是一种方法。 我假定space是单词分隔符,我使用正则expression式来获得第1列中每个列标题的计数。标点符号的单词可能不会返回您期望的内容,因此请在您的示例中查看它们。 注意下面, Dog将匹配Dog's 如果这不是你想要的,容易改变

阅读代码中的注释您将需要将“sheet1”更改为正确的工作表名称。

 Option Explicit 'Set reference to Microsoft VBScript Regular Expressions 5.5 Sub WordCounting() Dim WS As Worksheet, vSrc As Variant, R As Range Dim RE As RegExp, MC As MatchCollection Dim sPattern As String Dim V As Variant Dim I As Long, J As Long Set WS = ThisWorkbook.Worksheets("sheet1") With WS 'read into vba array for speed Set R = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)) _ .Resize(columnsize:=.Cells(1, .Columns.Count).End(xlToLeft).Column) vSrc = R End With 'get the word counts Set RE = New RegExp With RE .IgnoreCase = True .Global = True For I = 2 To UBound(vSrc, 1) V = Split(vSrc(I, 1)) vSrc(I, 2) = UBound(V) + 1 'Count of ALL Words For J = 3 To UBound(vSrc, 2) .Pattern = "\b" & vSrc(1, J) & "\b" Set MC = .Execute(vSrc(I, 1)) vSrc(I, J) = MC.Count 'Count of Individual Word in column header Next J Next I End With R = vSrc End Sub 

这是一个输出的例子。 这个algorithm应该缩放到您的大小工作表。

在这里输入图像说明

我会创build两个VBA函数来查找您的解决scheme:

  1. 使用分隔符空间查找总字数的函数:

在这里输入图像说明

码:

 Public Function WordCount(allItems As String) As Long Dim itemArray() As String Dim totalsum As Variant totalsum = 0 itemArray() = Split(allItems, " ") totalSum = UBound(itemArray) + 1 WordCount = totalsum End Function 
  1. 函数来计算匹配头的单元格中的string(头必须在第1行):

在这里输入图像说明

 Public Function HeaderWordCount(allItems As String) As Long Dim itemArray() As String totalsum = 0 itemArray() = Split(allItems, " ") For i = LBound(itemArray) To UBound(itemArray) If itemArray(i) = Cells(1, ActiveCell.Column).Value Then totalsum = totalsum + 1 End If Next i HeaderWordCount = totalsum End Function 

对于你正在做的事情,我会使用LEN和SUBSTITUTE / REPLACE的组合(这取决于你是否分别在Excel / VBA中进行)。 要计算单元格中的单词数量,可以计算单元格中的空格数量,然后添加1,该公式将如下所示:

 =LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1 

要计算string包含在单元格中的次数,这是一个类似的想法; 公式如下:

 =LEN(A1)-LEN(SUBSTITUTE(A1,"EnterString","")) 

NB-请确保将“EnterString”replace为包含您要search的标题string的正确单元格引用…

希望这有助于TheSilkCode