将数据复制到添加的工作表

时间:2015-06-09 17:36:28

标签: excel excel-vba copy-paste worksheet vba

下面的代码为2个其他工作簿中的每个分页符添加了一个新工作表到摘要工作簿。我想将其他工作簿中的数据复制到摘要工作簿中的每个添加的工作表。所有数据都只保留复制到sheet1。预先感谢您的任何帮助。

For n = 1 To Workbooks(file1name).Worksheets("Sheet1").HPageBreaks.Count

    i = i + 1 'integer that tracks the pages being added

    'SourceRange is a the range of data being copied
Set SourceRange = Workbooks(file1name).Worksheets("Sheet1").Range("A" & pgBreak, "Q" & Workbooks(file1name).Worksheets("Sheet1").HPageBreaks(n).Location.Row - 1)
        SourceRange.Copy
        summary.Sheets.Add 'summary is the summary workbook I would like to copy the data to
        summary.Sheets(i).Activate
        ActiveSheet.Paste


      For j = 1 To Workbooks(file2name).Worksheets("Sheet1").HPageBreaks.Count

                If matchVar = matchVar2 Then 'If the variable in workbook 1 matches the variable in workbook 2 than copy the information in between the page breaks
                    i = i + 1
                   Set SourceRange = Workbooks(file2name).Worksheets("Sheet1").Range("A" & pgBreak2, "Q" & Workbooks(file2name).Worksheets("Sheet1").HPageBreaks(j).Location.Row - 1)
                   SourceRange.Copy
                   summary.Sheets.Add
                   summary.Sheets(i).Activate
                   ActiveSheet.Paste
            End If

       Next

1 个答案:

答案 0 :(得分:1)

Excel在活动工作表之前默认添加新工作表,因此每次添加新工作表时都会移动“Sheet1”,因为它是活动工作表。
如果您看到workheet.add方法的文档,您会看到新创建的工作表也已激活,因此不需要再次激活它,只需粘贴您的数据;)