0

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

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
4

1 回答 1

0
  1. 确保将子例程放在 aModule中,而不是放在 ThisWorkbook. 您可以通过右键单击工作簿名称(从 VBA 编辑器)并转到Insert > Module来插入新模块。
  2. 确保您要使用/参考的工作簿已打开。
  3. 确保所有工作簿都位于同一个工作簿集合中。除非您手动创建额外的 Excel 实例,否则这不是问题。
  4. Workbooks()就像使用工作表一样,使用对象引用工作簿。

    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在与外部工作簿引用结合使用时遇到了问题。

更新

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

于 2013-10-21T21:52:31.360 回答