VB搜索多张excel表格

VB搜索多张excel表格,excel,vba,Excel,Vba,我试图写这个VB代码来快速搜索数据,但只搜索一张表。我正试图找出如何修改代码以搜索整个工作簿,但结果却很差。我有编程的基本知识,正在寻找一些指导 Private Sub searchButton_Click() Dim totRows As Long, i As Long totRows = Worksheets("Sheet3").Range("A1").CurrentRegion.Rows.Count If userInputBox.Text = "" Then

我试图写这个VB代码来快速搜索数据,但只搜索一张表。我正试图找出如何修改代码以搜索整个工作簿,但结果却很差。我有编程的基本知识,正在寻找一些指导

Private Sub searchButton_Click()
    Dim totRows As Long, i As Long
    totRows = Worksheets("Sheet3").Range("A1").CurrentRegion.Rows.Count

    If userInputBox.Text = "" Then
        MsgBox "Please enter a value"    
    End If

    For i = 1 To totRows
        If Trim(Sheet3.Cells(i, 2)) <> Trim(userInputBox.Text) And i = totRows Then
            MsgBox "Value not found!"
        End If

        If Trim(Sheet3.Cells(i, 2)) = Trim(userInputBox.Text) Then    
            networkValue.Text = Sheet3.Cells(i, 3)
            cernerValue.Text = Sheet3.Cells(i, 4)
            ipValue.Text = Sheet3.Cells(i, 5)
            Exit For
        End If
    Next i
End Sub
专用子搜索按钮\u单击()
我和你一样长,我和你一样长
totRows=工作表(“表3”).范围(“A1”).当前区域.Rows.Count
如果userInputBox.Text=”“,则
MsgBox“请输入一个值”
如果结束
对于i=1到totRows
如果Trim(Sheet3.Cells(i,2))Trim(userInputBox.Text)且i=totRows,则
MsgBox“未找到值!”
如果结束
如果Trim(Sheet3.Cells(i,2))=Trim(userInputBox.Text),则
networkValue.Text=Sheet3.Cells(i,3)
cernerValue.Text=Sheet3.Cells(i,4)
ipValue.Text=Sheet3.Cells(i,5)
退出
如果结束
接下来我
端接头

您只需将代码包装在For循环中,并引用循环中使用的工作表变量,即:

Private Sub searchButton_Click()

Dim totRows As Long, i As Long, ws As Worksheet

For Each ws In Worksheets
    totRows = ws.Range("A1").CurrentRegion.Rows.Count

    If userInputBox.Text = "" Then
        MsgBox "Please enter a value"
    End If

    For i = 1 To totRows
        If Trim(ws.Cells(i, 2)) <> Trim(userInputBox.Text) And i = totRows Then
            MsgBox "Value not found!"
        End If
        If Trim(ws.Cells(i, 2)) = Trim(userInputBox.Text) Then
            networkValue.Text = ws.Cells(i, 3)
            cernerValue.Text = ws.Cells(i, 4)
            ipValue.Text = ws.Cells(i, 5)
            Exit For
        End If
    Next i
Next ws

End Sub
专用子搜索按钮\u单击()
Dim totRows等长,i等长,ws等长工作表
对于工作表中的每个ws
totRows=ws.Range(“A1”).CurrentRegion.Rows.Count
如果userInputBox.Text=”“,则
MsgBox“请输入一个值”
如果结束
对于i=1到totRows
如果Trim(ws.Cells(i,2))Trim(userInputBox.Text)和i=totRows,那么
MsgBox“未找到值!”
如果结束
如果Trim(ws.Cells(i,2))=Trim(userInputBox.Text),那么
networkValue.Text=ws.Cells(i,3)
cernerValue.Text=ws.Cells(i,4)
ipValue.Text=ws.Cells(i,5)
退出
如果结束
接下来我
下一个ws
端接头
大量关于循环的在线资料

Howeverm,考虑使用<代码>查找< /COD>方法避免循环。