gpt4 book ai didi

vba - 如何查找并突出显示 ActiveSheet 中所有出现的多个字符串?

转载 作者:行者123 更新时间:2023-12-02 18:11:41 24 4
gpt4 key购买 nike

我已经找到了解决方案,但代码太长了。然后我决定搜索一种将我想要查找和突出显示的所有单词插入到单个查找方法中的方法。我遇到了一些使用数组来执行此操作的想法,并使用这 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。

最佳答案

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

你需要移动

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

就在之前

next i

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

关于vba - 如何查找并突出显示 ActiveSheet 中所有出现的多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com