簡體   English   中英

將附加的數據復制到另一個工作表

[英]Copy appended data to a different worksheet

我在同一工作簿中有以下工作,如何在另一個工作簿中使用摘要表?

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. 確保將子例程放置在Module ,而不是在ThisWorkbook 您可以通過右鍵單擊工作簿名稱(從VBA編輯器中)並轉到插入 > 模塊插入新 模塊
  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中使用“激活”或“選擇”命令。 只需分配變量並直接引用值即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM