将附加数据复制到其他工作表

时间:2013-10-21 21:14:13

标签: excel vba excel-vba

我有以下工作在同一工作簿中如何在不同的工作簿中使用摘要表?

Sub SummurizeSheets()
Dim ws As Worksheet

Application.ScreenUpdating = False
Sheets("Summary").Activate

For Each ws In Worksheets
    If ws.Name <> "Summary" Then
        ws.Range("D2:D6, D8:D15").Copy
        Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).PasteSpecial (xlPasteValues)
    End If
Next ws
End Sub

1 个答案:

答案 0 :(得分:0)

  1. 确保将子例程放在Module中,而不是放在ThisWorkbookWorkbooks()。您可以通过右键单击工作簿名称(来自VBA编辑器)并转到插入&gt;来插入新模块。的模块即可。
  2. 确保您要使用/引用的工作簿已打开。
  3. 确保工作簿都位于同一工作簿集合中。除非您手动创建Excel的其他实例,否则这不是问题。
  4. 像您一样使用Sub test() Dim b2 As Workbook 'We will use this variable as a reference to the external workbook that contains the "Summary" worksheet. Set b2 = Excel.Workbooks("testbook2") 'We assign the external workbook (which I named "testbook2" for the purposes of this example) to our 'b2' variable. Dim ws1 As Worksheet Dim ws2 As Worksheet 'We will use these variables as references to the worksheets we're using. Set ws1 = Excel.ActiveSheet 'We set ws1 to equal our current sheet (which presumably is where you'll be copying data from). Set ws2 = b2.Worksheets("Summary") 'We set ws2 to equal the sheet (named "Summary") in the external workbook (named "testbook2"). ws1.Range("D2:D6").Copy 'We copy the data from the active sheet, which we reference using our 'ws1' variable. 'Note: I had issues with using multiple ranges in the same object so I removed this from your code. ws2.Cells(Rows.Count, 4).End(xlUp).PasteSpecial xlPasteValues 'You only need to use the ws2 variable since we've already defined it as the "Summary" sheet you want. End Sub 对象引用工作簿 使用工作表。

    ThisWorkbook
  5. 我不确定为什么我遵循第一条规则,但我似乎记得在将{{1}}与外部工作簿引用结合使用时遇到问题。

    更新

    我编辑了代码,向您展示了如何执行此操作的更好示例。您几乎不需要在VBA中使用“激活”或“选择”命令。只需分配变量并直接引用这些值。