excel - 如何计算一个单元格中特定单词的总数并使用 VBA 对其他单元格做同样的事情?

标签 excel vba

如何计算一个单元格中出现的“alt”和“first”的总数,并对其他单元格也做同样的事情,同时忽略过程中的空单元格?例如,如果一个单元格有 first、first、alt、first、first、first,它应该给我 firstcounter = 5(其中 firstcounter 是 first 的总计数)和 altcounter= 1(altcounter 是 alt 的总计数)。之后,我可以使用找到的 firstcounter 和 altcounter 的值将它们连接成一个字符串,如 B 列中所示,形式为“first-”& firstcounter、“alt-”& altcounter。

Dim ia As Long
Dim lastrow2 As Long
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets(1)
lastrow2 = ws1.Range("A" & ws1.Rows.count).End(xlUp).Row
For ia = 2 To lastrow2
  Dim arr() As Variant
    ' Split the string to an array
arr = Split(ws1.Cells(ia, "A"), ",").Value
'what should i do after split

enter image description here

最佳答案

将以下内容输入代码模块...

Function CountWords$(r)
    Dim a&, f&, w
    For Each w In Split(r, ",")
        If w = "alt" Then a = a + 1
        If w = "first" Then f = f + 1
    Next
    If (a + f) Then CountWords = "first-" & f & ",alt-" & a
End Function

然后在 B2 单元格中输入这个公式:

=CountWords(A2)

现在根据需要向下复制它。


更新

要在 VBA 中使用上述函数而不在工作表中输入公式,您可以这样做...

Sub Cena()
    Dim i&, v
    With [a2:a8]
        v = .Value2
        For i = 1 To UBound(v)
            v(i, 1) = CountWords(v(i, 1))
        Next
        .Offset(, 1) = v
    End With
End Sub

Function CountWords$(r)
    Dim a&, f&, w
    For Each w In Split(r, ",")
        If w = "alt" Then a = a + 1
        If w = "first" Then f = f + 1
    Next
    If (a + f) Then CountWords = "first-" & f & ",alt-" & a
End Function

更新#2

针对您在评论中提出的问题,您可以改用此变体...

Sub Cena()
    Dim i&, v
    With [a2].Resize(Cells(Rows.Count, 1).End(xlUp).Row - 1)
        v = .Value2
        For i = 1 To UBound(v)
            v(i, 1) = CountWords(v(i, 1))
        Next
        .Cells = v
    End With
End Sub

Function CountWords$(r)
    Dim a&, f&, w
    For Each w In Split(r, ",")
        If w = "alt" Then a = a + 1
        If w = "first" Then f = f + 1
    Next
    If (a + f) Then CountWords = "first-" & f & ",alt-" & a
End Function

关于excel - 如何计算一个单元格中特定单词的总数并使用 VBA 对其他单元格做同样的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60702011/

相关文章:

vba - 从第 4 行开始选择 Word VBA

excel - 为什么我会遇到堆栈溢出错误

vba - Worksheet_SelectionChange 和 Workbook_SheetSelectionChange 事件的用法

excel - 如何用VBA在Excel指定单元格位置插入图片

c# - 调用 SaveAs 方法时出错

excel - 在 Excel/VBA 中将日期和时间连接到单个单元格中

Python将多个不相等的列表写入Excel文件

vba - 在 VBA 中使用 Unicode 文件名(使用 Dir、FileSystemObject 等)

vba - 创建宏以向上移动列中的数据?

vba - 获取数据库的VBProject