【问题标题】:I'm trying to add a count to the number of searches found in my code我正在尝试将计数添加到我的代码中找到的搜索次数
【发布时间】:2016-05-12 17:56:38
【问题描述】:

我的代码如下:

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

【问题讨论】:

  • 这不是很清楚 - 你能解释一下你想要计数器做什么,以及你希望它如何工作吗?
  • 计算在 Excel 工作表 @Grade'Eh'Bacon 中找到 SearchString 中的单词的次数
  • 我认为如果您解释(用文字,而不是 VBA 代码)您试图用您的程序完成什么,这会有所帮助。现在,我实际上无法说出它发生了什么,并且您以“If Not acell”开头的结构布局方式让我感到困惑。就目前而言,我预计这在结束前不会超过 1 场比赛 [尽管我可能在快速阅读时误解了],所以它似乎没有达到你的预期。
  • 我真的不明白这 3 个 DV。问题和问题的定义非常明确。 @Grade'Eh'Bacon - If Not aCell Is Nothing Then 只是说如果第一次找到 SearchString(在 Set aCell = ...,然后继续该过程。
  • @ScottHoltzman 这不是我觉得令人困惑的特定表达式,它是 Do While 循环的方法,并且没有解释计数器的用途 - 甚至不应该做出有根据的猜测这些东西……

标签: excel vba counter worksheet


【解决方案1】:

使用当前代码,您甚至不需要使用计数器。相反,您可以将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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多