【问题标题】:How to find and highlight all occurrences of multiple strings within the ActiveSheet?如何在 ActiveSheet 中查找并突出显示所有出现的多个字符串?
【发布时间】:2015-08-25 16:22:07
【问题描述】:

我已经找到了解决方案,但是代码太长了。然后我决定搜索一种将我想要查找并突出显示的所有单词插入单个查找方法的方法。我遇到了一些使用数组的想法,并使用这 3 个代码来编写我的(thisthisthis),但我是 VBA 的新用户,所以我的最终代码有问题,它仅突出显示数组的最后一个字符串。我认为问题出在逻辑上,但我不知道 VBA 的基础知识,所以我不知道如何纠正它。

我的实际代码:

Sub Sample()
Dim fnd As String
Dim MyAr
Dim i As Long
Dim rng As Range, FoundCell As Range, LastCell As Range, myRange As Range

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

fnd = "hugo/vw/osnabrück"

MyAr = Split(fnd, "/")

    For i = LBound(MyAr) To UBound(MyAr)

        Set FoundCell = myRange.Find(what:=MyAr(i), after:=LastCell)

        If Not FoundCell Is Nothing Then
            FirstFound = FoundCell.Address
        End If
Set rng = FoundCell
            Do Until FoundCell Is Nothing
                Set FoundCell = myRange.FindNext(after:=FoundCell)
                    Set rng = Union(rng, FoundCell)
                If FoundCell.Address = FirstFound Then Exit Do
            Loop
    Next i

If Not rng Is Nothing Then
    rng.EntireRow.Interior.ColorIndex = 3
End If
End Sub

例如,使用此代码,我可以找到并突出显示所有“Osnabrück”,但它不会突出显示任何 Hugo 或 VW。

【问题讨论】:

    标签: vba excel for-loop excel-2010


    【解决方案1】:

    这是因为您只在代码的最后进行了一次高亮显示,而数组中的最后一个选择恰好是 osnabruck。

    你需要移动

    If Not rng Is Nothing Then
        rng.EntireRow.Interior.ColorIndex = 3
    End If
    

    就在之前

    next i
    

    这样它就会为数组中的每个元素执行 if。

    【讨论】:

    • 同意,这将解决问题。值得注意的是:看起来 OP 试图使用 Union 来构建 Range 并在最后做一个突出显示。如果是这样,则问题在于使用Set rng=FoundCell,它为每个i 运行。如果它是Set rng = Union(rng, FoundCell),这将起作用。问题是第一个Union 会因为rng is Nothing 而失败。这可以通过用If rng is Nothing Then : Set rng = FoundCell : Else : ...union... : End If 包装来解决。
    猜你喜欢
    • 2013-02-19
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多