我正在尝试为我的代码中找到的搜索次数添加计数

时间:2016-02-03 13:41:09

标签: excel vba counter worksheet

我的代码如下:

Expect: 100-continue

我添加了以下代码,但不知道如何添加计数器部分:

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

1 个答案:

答案 0 :(得分:1)

使用当前代码,您甚至不需要使用计数器。相反,您可以将FoundAt加载到数组中,然后使用Ubound来获取总计数。 请注意,由于数组基于0,因此必须添加1。

在最终Msgbox

之前添加这些行
Dim iCount() as String
iCount = Split(FoundAt,", ")

MsgBox "The Search String has been found " & UBound(iCount)+1 & " times at these locations: " & FoundAt