【问题标题】:Count how many words contain any of specific letters计算有多少单词包含任何特定字母
【发布时间】:2021-12-14 21:20:04
【问题描述】:

我正在尝试计算包含任何字母“j”、“a”、“d”、“e”的单词总数。

例如,如果这个词是“夹克”,那么它将被计算在内。整个宏遍历 A 列和第 3 行到第 373659 行中的单词列表。

Dim count As Long
Dim word As String
Dim row As Long
    
count = 0
    
For row = 3 To 373659
    word = Cells(row, 1).Value
    If InStr(word, "j") Or InStr(word, "a") Or InStr(word, "d") Or     InStr(word, "e") Then
        count = count + 1
    End If
Next row

这段代码正确吗?可以改进吗?

【问题讨论】:

  • 请注意,这条Ors 链目前有效,因为它只涉及Ors。如果您决定使条件更复杂一点,则可能是fall apart。您需要明确地将InStrs 的结果与零进行比较以避免这种情况。
  • 我会使用VBScript.RegExp.Test 方法来测试正则表达式是否存在。
  • 如何用空字符串替换每个字母,得到前后的计数并减去两者。或者使用一个案例,以便在找到一个实例后尽早退出:stackoverflow.com/questions/7015471/…

标签: excel vba


【解决方案1】:

这应该更有效:

Sub Tester()
    
    Dim count As Long
    Dim word As String
    Dim row As Long, arr, e, data
        
    count = 0
    arr = Array("a", "e", "d", "j") 'ordering most-common to least-common
                                    '  will give you a slight boost
    
    data = Range("A3:A373659").Value 'read the whole range,
                                     '  not cell-by-cell
    
    For row = 1 To UBound(data, 1)
        word = lcase(data(row, 1))

        'either test letter-by-letter...
        For Each e In arr
            If InStr(word, e) > 0 Then 
                count = count + 1
                Exit For  'exit after first match: no need to test others
            End If
        Next e

        'or use `Like`
        If word Like "*[aedj]*" Then
            count = count + 1
        End If

    Next row

End Sub

【讨论】:

  • word Like "*[adej]*"?..
  • 哈哈——当然……我总是忘记[]的版本……
猜你喜欢
  • 2021-08-03
  • 2017-03-19
  • 2023-02-21
  • 2021-07-30
  • 2015-02-11
  • 2021-12-12
  • 2015-08-16
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多