使用VBA在工作表中搜索字符串

4
我尝试在工作簿的所有工作表中搜索特定字符串“ERROR”,并将其加粗并将找到的单元格颜色设置为红色。
我可以遍历每个工作表,但无法使用VBA的Find函数。

3
录制宏并使用CTRL+F手动搜索。查看你得到了什么代码? - Siddharth Rout
非常感谢。不过单元格的内容是一个公式而不是文本,所以我要用“查找数值”进行搜索。但是我无法将其加粗并使单元格变为红色。有什么想法吗? - Kiran
是的,您必须使用“查找值”进行搜索,并且您还必须在“范围”下拉菜单中选择“工作簿”。然后,将找到的单元格设置为粗体和红色。请参阅此链接http://siddharthrout.wordpress.com/2011/07/14/find-and-findnext-in-excel-vba/。 - Siddharth Rout
为什么不直接使用条件格式?这似乎是显而易见的答案。 - ApplePie
如果您有一个类似于=IF(B1=C1,"Success","ERROR")的公式,那么像Chris提到的那样使用xlFormulas,如果您想要检查公式中的字符串。但是,如果您只关心公式的输出结果为“ERROR”(在上面的示例中,如果B1<>C1),则使用xlValues。另一种情况:如果您有=0/0,它会给您#DIV/0!,那么在搜索#DIV/0!时请使用xlValues - Siddharth Rout
3个回答

12

这是一个使用 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

  • 1 我在原帖的留言中添加了一个小的澄清。
- Siddharth Rout
@chris neilsen - 我该如何获取包含我的字符串的行中的值? - yesIamFaded

1
如果您在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

您可以从这里下载示例文件


-1
这样怎么样:
If Not WorkBook.Sheets("Sheet1").Range("A1:Z150").Find("Cookie") Is Nothing 
    MsgBox "Found a Cookie"
End If

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接