[英]Excel VBA - Copying all Worksheets from a specific workbook into an active workbok
[英]Search all Excel worksheets in workbook from Access with string from form on event with VBA
下面的代碼從 Access 窗體上的按鈕事件打開 Excel 電子表格,並在命名工作表上的窗體控件中搜索字符串。 我想修改此代碼以搜索所有工作表。 excel 工作簿是從表單控件中提取的變量。
```
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
您需要測試查找是否成功。
如果是,則退出循環(假設您想在找到搜索searchstring
后停止;如果不是這種情況,請刪除Exit For
。)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.