我想问你是否可以帮助解决下面的代码。在我的工作簿中的每个工作表上都有相同类型的表,但是在每个工作表上,表具有不同的位置和值。我需要浏览所有工作表,在每个工作表上搜索表值,然后使用值执行其他操作。我使用Find函数来确定表的标题和随后的表范围。 Find函数不能正常工作,因为它保持找到" Header"的地址。每张其他纸张的第一张纸张的单元格。在循环到另一个工作表之前,有没有办法重置找到的标头地址值?提前谢谢。
Sub FindInDynamicRanges()
Dim wb1 As Workbook
Dim ws As Worksheet
Dim FoundCell, FoundTab, TabEntries As Excel.Range
Dim FirstAddr As String
Dim FirstRow, LastRow As Long
Set wb1 = ThisWorkbook
'Find all occurences of any table value on all sheets in dynamic ranges
For Each ws In wb1.Worksheets
Set ws = ActiveSheet
'Find "Header" cell
Set FoundCell = ws.Columns(2).Find(What:="Header", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
MsgBox FoundCell.Address
'Set number of first entry row and last entry row
FirstRow = FoundCell.Row + 1
LastRow = ws.Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlValues, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, MatchCase:=False).Row
ws.Range("B" & FirstRow & ":B" & LastRow).Name = "TabEntries"
MsgBox Range("TabEntries").Address
With ws.Range("TabEntries")
Set LastCell = .Cells(.Cells.Count)
End With
Set FoundTab = ws.Range("TabEntries").Find(What:="*", After:=LastCell, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not FoundTab Is Nothing Then
FirstAddr = FoundTab.Address
End If
Do Until FoundTab Is Nothing
'do some staff with found values
Set FoundTab = ws.Range("TabEntries").FindNext(After:=FoundTab)
If FoundTab.Address = FirstAddr Then
Exit Do
End If
Loop
Next ws
End Sub
答案 0 :(得分:3)
因为它从第一张纸上找到每个其他纸张的“标题”单元格的地址。
那是因为你告诉它......
For Each ws In wb1.Worksheets
Set ws = ActiveSheet
您不需要Set ws = ActiveSheet
当您说For Each ws
时,ws
会自动初始化。所以只需删除第二行。