我有一个摘要表Consolidated Tracker
和不会静态设置的数据表,因为它们是日期,例如Sheet1 renamed May 2018
Sheet2 renamed October 2018
Sheet3 renamed May 2019
等。
以下代码在两个静态设置的工作表match
和B
的{{1}}列中检查Consolidated Tracker
。
如果找到了May 2018
,它将从match
中的单元格C4
中获取值,并将May 2018
中的C4
设置为此值。
我接下来要实现的是检查:
Consolidated Tracker
,如果找到匹配项,则在Sheet3
中设置D4
。Consolidated Tracker
,如果找到匹配项,则在Sheet4
中设置E4
。Consolidated Tracker
,如果找到匹配项,则在Sheet5
中设置F4
。我已经走了这么远,但是我不确定如何从这里开始。
谢谢。
Consolidated Tracker
答案 0 :(得分:1)
这是您想要的吗?
它使用工作表索引,但是我对此感到不安,因为工作表可以轻松地重新排序,并且您的代码会炸毁。
按目前的情况,代码将从第一页到倒数第二页(假设目标页是最后一页)运行,因此您可能需要调整j
循环。
Public Sub UpdateData()
Dim WsDest As Worksheet 'destination workbook to write in
Set WsDest = ThisWorkbook.Worksheets("Consolidated Tracker")
Dim LastRow As Long 'last used row in workbook
LastRow = WsDest.Cells(WsDest.Rows.Count, "B").End(xlUp).Row
Dim iRow As Long, MatchedRow As Variant, j As Long, c As Long
c = 3
For j = 1 To Sheets.Count - 1
For iRow = 1 To LastRow 'loop through all rows from row 1 to last used row and update each row
MatchedRow = Application.Match(WsDest.Cells(iRow, "B"), Worksheets(j).Columns("B"), 0) 'get the row number of the match
If IsNumeric(MatchedRow) Then 'if a match was found then copy values
WsDest.Cells(iRow, c).Value = Worksheets(j).Cells(MatchedRow, "C").Value
End If
Next iRow
c = c + 1
Next j
End Sub
这是一种不依赖于工作表索引的更好方法。
Public Sub UpdateData()
Dim WsDest As Worksheet 'destination workbook to write in
Set WsDest = ThisWorkbook.Worksheets("Consolidated Tracker")
Dim LastRow As Long 'last used row in workbook
LastRow = WsDest.Cells(WsDest.Rows.Count, "B").End(xlUp).Row
Dim iRow As Long, MatchedRow As Variant, c As Long, ws As Long
c = 3
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> WsDest.Name Then
For iRow = 1 To LastRow 'loop through all rows from row 1 to last used row and update each row
MatchedRow = Application.Match(WsDest.Cells(iRow, "B"), ws.Columns("B"), 0) 'get the row number of the match
If IsNumeric(MatchedRow) Then 'if a match was found then copy values
WsDest.Cells(iRow, c).Value = ws.Cells(MatchedRow, "C").Value
End If
Next iRow
c = c + 1
End If
Next ws
End Sub