我正在尝试对在我的代码中找到的搜索次数进行计数
I'm trying to add a count to the number of searches found in my code
我的代码如下:
Dim ws As Worksheet
Dim ExitLoop As Boolean
Dim SearchString As String, FoundAt As String
Set ws = Worksheets("detail_report")
On Error GoTo Err
Set oRange = ws.Cells
SearchString = "front input"
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bCell = aCell
FoundAt = aCell.Address
Do While ExitLoop = False
Set aCell = oRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & aCell.Address
Else
ExitLoop = True
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
MsgBox "The Search String has been found these locations: " & FoundAt
Exit Sub
Err:
MsgBox Err.Description
End Sub
我添加了以下代码,但不知道如何添加计数器部分:
Dim S As String
Dim count As Integer
使用您现有的代码,您甚至不需要使用计数器。相反,您可以将 FoundAt
加载到数组中,然后使用 Ubound
获取总数。 请注意,您必须加 1,因为数组是基于 0 的。
在最后的 Msgbox
之前添加这些行
Dim iCount() as String
iCount = Split(FoundAt,", ")
MsgBox "The Search String has been found " & UBound(iCount)+1 & " times at these locations: " & FoundAt
我的代码如下:
Dim ws As Worksheet
Dim ExitLoop As Boolean
Dim SearchString As String, FoundAt As String
Set ws = Worksheets("detail_report")
On Error GoTo Err
Set oRange = ws.Cells
SearchString = "front input"
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bCell = aCell
FoundAt = aCell.Address
Do While ExitLoop = False
Set aCell = oRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & aCell.Address
Else
ExitLoop = True
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
MsgBox "The Search String has been found these locations: " & FoundAt
Exit Sub
Err:
MsgBox Err.Description
End Sub
我添加了以下代码,但不知道如何添加计数器部分:
Dim S As String
Dim count As Integer
使用您现有的代码,您甚至不需要使用计数器。相反,您可以将 FoundAt
加载到数组中,然后使用 Ubound
获取总数。 请注意,您必须加 1,因为数组是基于 0 的。
在最后的 Msgbox
Dim iCount() as String
iCount = Split(FoundAt,", ")
MsgBox "The Search String has been found " & UBound(iCount)+1 & " times at these locations: " & FoundAt