The code below opens an Excel spreadsheet from a button event on an Access form, and searches for a string in a form control on a named Worksheet. I would like to adapt this code to search through all Worksheets. The excel workbook is a variable lifted from a form control.
``` Private Sub Command132_Click() On Error GoTo Err_Command132_Click Dim filename As String Dim searchstring As String Dim xlApp As Excel.Application 'Excel object Dim XlBook As Excel.Workbook 'Workbook object Dim Xlsheet As Excel.Worksheet 'Worksheet object Set xlApp = CreateObject("Excel.Application") searchstring = Me.Matrixsrch filename = Me.GroupsMatrixLoccntrl Set XlBook = xlApp.Workbooks.Open(filename) xlApp.Visible = True xlApp.ActiveWindow.WindowState = xlMaximized Set Xlsheet = XlBook.Sheets("GroupMatrix") With Xlsheet .Cells.Find(What:=searchstring, After:=.Cells(1, 1), LookIn:=xlvalues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate End With Exit_Command132_Click: Exit Sub Err_Command132_Click: MsgBox "Error " & Err.Number & "; " & Err.Description Debug.Print "Error " & Err.Number & "; " & Err.Description Resume Exit_Command132_Click End Sub
I have tried using the code below to iterate through the worksheets. The search is run on the first worksheet and a value found, but subsequently an *Error 91; Object variable or With block variable not set* is generated. Can anyone help me with the iteration please? thanks
For Each Xlsheet In XlBook.Worksheets With Xlsheet .Cells.Find(What:=searchstring, After:=.Cells(1, 1), LookIn:=xlvalues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate End With Next
You need to test if the find was successful.
If it was, then exit the loop (assuming you want to stop after the
searchstring is found; if this is not the case, remove the
For Each Xlsheet In XlBook.Worksheets With Xlsheet Dim foundCell as Range Set foundCell = .Cells.Find(What:=searchstring, _ After:=.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not foundCell Is Nothing Then .Activate foundCell.Select Exit For End If End With Next