简体   繁体   中英

VB search multiple excel sheets

I am trying to write this VB code to do a quick search for data but only searches one sheet. I am trying to figure out how I can modify my code to search the whole workbook but have come up short. I have basic knowledge of programming, looking for some guidance.

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

You just need to wrap your code in a For loop and reference the worksheet variable used in the loop, viz:

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

Plenty of material online on loops.

Howeverm, consider avoiding a loop by using the Find method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM