我希望能够进行以下两项行动;我知道Excel公式,但我希望有一种方法可以用VBA编程。
= LEN(TRIM($ A2)) - LEN(SUBSTITUTE($ A2,“”,“”))+ 1
A列中的单元格包含自由格式文本,范围为500-2,500个单词,分隔符为空格。带有文本的单元格数量因工作簿和工作簿而异。
到目前为止,我尝试输入以下代码,但没有运气。我收到类型不匹配
代码:
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
=(LEN($ A2)-LEN(SUBSTITUTE(UPPER($ A2),UPPER(C $ 2), “”)))/ LEN(C $ 1)
与上述问题不同,我无法启动脚本。
答案 0 :(得分:3)
VBA宏可能会为此目的执行得最快。这是一种方法。我假设space
是单词分隔符,我使用正则表达式来获取第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
以下是输出示例。此算法应该可以缩放到您的大小工作表。
答案 1 :(得分:2)
我会创建两个VBA函数来找到你的解决方案:
代码:
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
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
答案 2 :(得分:0)
对于你要做的事情,我会使用LEN和SUBSTITUTE / REPLACE的组合(取决于你是否分别在Excel / VBA中这样做)。要计算单元格中的单词数,可以计算单元格中的空格数,然后加1,公式如下:
=LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1
要计算字符串包含在单元格中的次数,这是一个类似的想法;公式如下:
=LEN(A1)-LEN(SUBSTITUTE(A1,"EnterString",""))
N.B.-确保将“EnterString”替换为包含您要搜索的标题字符串的正确单元格引用...
希望这有帮助, TheSilkCode