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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11813720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:41:40  来源:igfitidea点击:

Search for a string in a Worksheet using VBA

excelvba

提问by Kiran

I am trying to search for a particular string "ERROR" in all the worksheets in the workbook and make it bold and color the found cell red.

我正在尝试在工作簿的所有工作表中搜索特定字符串“ERROR”,并将其设置为粗体并将找到的单元格着色为红色。

I am able to parse through each worksheet. I am not able to use the Findfunction of VBA.

我能够解析每个工作表。我无法使用FindVBA的功能。

回答by chris neilsen

Here's an example of using Findand formatting the found cells

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

回答by Excelhub Org

if you are searching in excel vba you can use following simple code with InStrcommand.

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

you can download example file from here

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

回答by Condemateguadua

How about this:

这个怎么样:

If Not WorkBook.Sheets("Sheet1").Range("A1:Z150").Find("Cookie") Is Nothing 
    MsgBox "Found a Cookie"
End If