下面的函数用于计算工作表中字符串的出现次数。以下是似乎有效的代码。
Option Explicit
Sub Main()
Dim ws As Worksheet: Set ws = Worksheets(1)
Dim SearchedCell As Range: Set SearchedCell = ws.Range("A1")
Dim FirstCell As Range
Dim Count As Integer
Set SearchedCell = ws.Cells.Find("stock", SearchedCell, xlValues)
Set FirstCell = SearchedCell
If Not SearchedCell Is Nothing Then
Count = Count + 1
End If
Do
Set SearchedCell = ws.Cells.Find("stock", SearchedCell, xlValues)
If SearchedCell Is Nothing Then
MsgBox Count
Exit Sub
End If
If Not SearchedCell = FirstCell Then
Count = Count + 1
End If
Loop While Not SearchedCell = FirstCell
MsgBox Count
End Sub
但是,如果我删除零件:
If SearchedCell Is Nothing Then
MsgBox Count
Exit Sub
End If
该代码不再适用于仅出现一次的字符串,而是适用于多次出现的字符串。我注意到,对于2次或以上的事件,find函数不会在末尾返回Nothing,而是实际上循环回到开头。如果仅出现1次,则第二个find函数返回Nothing。为什么会这样?