[英]Excel VBA copy sheet data from multiple sheets based on list
好的,這是我基於下面代碼的更新。 我需要的是從“主”中列出的任何工作表中獲取任何數據,以填寫“組合”工作表。 每個工作表中只有三列數據。 每個工作表的數據應從“組合”的A列開始。
Private Sub CommandButton1_Click()
Dim lLastRow As Long
Dim i As Integer
lLastRow = Worksheets("Master").Cells(Rows.Count, 1).End(xlUp).Row
last_col = 0
For i = 2 To lLastRow
MySheet = Worksheets("Master").Cells(i, 1).Value
Worksheets(MySheet).Columns(1).Copy Worksheets("Combined").Columns(last_col + 1)
last_col = Worksheets("Combined").Cells(1, Columns.Count).End(xlToLeft).Column
Next
End Sub
嘗試以下方法。
根據OP注釋進行編輯 (數據“堆疊”)
Private Sub CommandButton1_Click()
Dim lLastRow As Long
Dim i As Integer
lLastRow = Worksheets("Master").Cells(Rows.Count, 1).End(xlUp).Row 'Last row of Master Sheet
lLastRowCombined = Worksheets("Combined").Cells(Rows.Count, 1).End(xlUp).Row 'Last row of Combined Sheet
For i = 2 To lLastRow 'scan all rows in Master Sheet
MySheet = Worksheets("Master").Cells(i, 1).Value 'MySheet stores the sheet name from list in Master, row i, column A
lLastRow2 = Worksheets(MySheet).Cells(Rows.Count, 1).End(xlUp).Row 'For that Sheet, get the last row
Worksheets(MySheet).Range("A1:C" & lLastRow2).Copy Worksheets("Combined").Range("A" & lLastRowCombined) 'copy the range into Combined Sheet
lLastRowCombined = Worksheets("Combined").Cells(Rows.Count, 1).End(xlUp).Row + 1 'Get the NEW Last row of Combined Sheet
Next
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.