【发布时间】:2020-05-09 07:30:45
【问题描述】:
search entire Excel workbook for text string and highlight cell 似乎正是我所需要的,但我无法让它在我的 Excel 工作簿上工作。我在 10 个工作表中有数百行。所有搜索到的字符串(数据包 01、数据包 02、数据包 03 等)将位于 B:8 到 worksheet(1) 的行端和 B:7 到其他 9 的行端工作表(工作表被命名并且字符串的InputBox 结果需要区分大小写)。 45547221 表示内部颜色变化,但是所有字符串都有不同颜色的单元格时颜色会太多,因此使用font.color.index 更改字符串颜色会更好。按原样尝试 45547221 代码会发现它在步进模式下跳过了 Do/Loop While 代码。
我会修改 45547221 中的代码,至少添加:
Dim myColor As Integer
myColor = InputBox("Enter Color Number (1-56)")
(配置后我可以使用 InputBox(es) 输入多达 5 个 FindStrings 和 5 个 ColorIndex 数字作为 Dim)
在Do/Loop While 我会更改.ColorIndex = myColor
我想让这段代码工作,因为它似乎符合我的需要 - 修改为在工作簿中查找字符串实例并重新着色字符串而不是单元格内部颜色,以及 (2) 让它识别 Do/Loop While 代码现在不是,但会将ColorIndex 数字应用于每个字符串。
Public Sub find_highlight()
'Put Option Explicit at the top of the module and
'Declare your variables.
Dim FindString As String
Dim wrkSht As Worksheet
Dim FoundCell As Range
Dim FirstAddress As String
Dim MyColor As Integer 'Added this
FindString = InputBox("Enter Search Word or Phrase")
MyColor = InputBox("Enter Color Number")
'Use For...Each to cycle through the Worksheets collection.
For Each wrkSht In ThisWorkbook.Worksheets
'Find the first instance on the sheet.
Set FoundCell = wrkSht.Cells.Find( _
What:=FindString, _
After:=wrkSht.Range("B1"), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
'Check it found something.
If Not FoundCell Is Nothing Then
'Save the first address as FIND loops around to the start
'when it can't find any more.
FirstAddress = FoundCell.Address
Do
With FoundCell.Font 'Changed this from Interior to Font
.ColorIndex = MyColor
'.Pattern = xlSolid
'.PatternColorIndex = xlAutomatic 'Deactivated this
End With
'Look for the next instance on the same sheet.
Set FoundCell = wrkSht.Cells.FindNext(FoundCell)
Loop While FoundCell.Address <> FirstAddress
End If
Next wrkSht
End Sub
【问题讨论】:
-
在您的问题中包含代码当您尝试修改它时,并准确解释它是如何不起作用的(或者如果这是问题,您会遇到什么错误)。由于链接的代码似乎可以正常工作,因此无法准确猜出它为什么不适合您。
-
First... 尝试使用
在这里设置代码但失败了。我用 5 个工作表构建了一个独立文件。修改为将 Dim MyColor 添加为 Integer,并将 MyColor = InputBox("Color") 和 .ColorIndex = [Number] 更改为 .ColorIndex = MyColor,然后将 With FoundCell.Interior 更改为 With FoundCell.Font 并删除 .Pattern = xlSolid 和 .PatternColorIndex = 自动。原始代码和修改后的代码在单机上工作。我把它放在工作簿中,我需要它作为 ThisWorkbook 模块,并在逐步突出显示 If Not FoundCell Is Nothing 时,它跳过了 Do 代码。 -
如果您将完整代码添加到问题中,有人会为您设置格式。
-
蒂姆,谢谢。认为 Stackhouse 参考就足够了。用代码编辑了帖子。