Excel 使用VBA在工作表中搜索字符串
我试图在工作簿中的所有工作表中搜索特定字符串“ERROR”,并将其加粗并将找到的单元格涂成红色Excel 使用VBA在工作表中搜索字符串,excel,vba,Excel,Vba,我试图在工作簿中的所有工作表中搜索特定字符串“ERROR”,并将其加粗并将找到的单元格涂成红色 我能够解析每个工作表。我无法使用VBA的Find功能。下面是一个使用Find并格式化找到的单元格的示例 Sub FindERROR() Dim SearchString As String Dim SearchRange As Range, cl As Range Dim FirstFound As String Dim sh As Worksheet ' S
我能够解析每个工作表。我无法使用VBA的
Find
功能。下面是一个使用Find
并格式化找到的单元格的示例
Sub FindERROR()
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = "ERROR"
Application.FindFormat.Clear
' loop through all sheets
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = sh.Cells.Find(What:=SearchString, _
After:=sh.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address
' format found cell
Do
cl.Font.Bold = True
cl.Interior.ColorIndex = 3
' find next instance
Set cl = sh.Cells.FindNext(After:=cl)
' repeat until back where we started
Loop Until FirstFound = cl.Address
End If
Next
End Sub
如果您在excel vba中搜索,可以使用以下简单代码和InStr命令
Private Sub CommandButton1_Click()
Dim RowNum As Long
RowNum = 1
Do Until Sheets("Data").Cells(RowNum, 1).Value = ""
If InStr(1, Sheets("Data").Cells(RowNum, 2).Value, TextBox1.Value, vbTextCompare) > 0 Then
On erro GoTo next1
ListBox1.AddItem Sheets("Data").Cells(RowNum, 1).Value
ListBox1.List(ListBox1.ListCount - 1, 1) = Sheets("Data").Cells(RowNum, 2).Value
End If
next1:
RowNum = RowNum + 1
Loop
End Sub
这个怎么样:
If Not WorkBook.Sheets("Sheet1").Range("A1:Z150").Find("Cookie") Is Nothing
MsgBox "Found a Cookie"
End If
是,录制宏并使用CTL F手动搜索。查看您得到的代码?非常感谢。但是,单元格的内容是公式而不是文本。因此,我通过“查找值”进行搜索。但我不能使它大胆,使细胞为红色。有什么想法吗?是的,您必须使用“查找值”进行搜索,还必须在
内的下拉列表中选择“工作簿”。然后用找到的单元格使其变为粗体和红色。查看此链接为什么不使用条件格式?这似乎是一个显而易见的答案。如果你有一个像=If(B1=C1,“成功”,“错误”)
这样的公式,那么如果你想检查公式中的sting,就使用Chris提到的xlFormulas
。但是,如果您只关心导致“错误”的公式输出(如果上例中为B1C1),则使用xlValues
。另一个场景:如果你有=0/0
,它会给你#DIV/0
然后在搜索#DIV/0时使用xlValues
代码>+1我在OP的线程中的注释中添加了一个小的澄清。@chris neilsen-我如何才能得到字符串所在行中的值?