基于列表的多张表中的Excel VBA副本表数据

时间:2017-04-27 16:46:14

标签: excel-vba excel-2010 vba excel

好的,这是基于下面代码的更新。我需要的是从'Master'中列出的任何工作表中获取任何数据以填写表'Combined'。每张表中只有三列数据。每张纸的数据应从“合并”的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

1 个答案:

答案 0 :(得分:0)

请尝试以下操作。

已编辑,根据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