Excel VBA,打开工作簿,复制并添加到另一个工作簿的最后一行

时间:2018-06-05 06:42:26

标签: excel vba excel-vba excel-2010

是否有人有任何代码或知道是否可能,从当前工作簿打开另一个工作簿并复制表列上的数据并粘贴到当前工作簿中表的最后一行。并删除源数据。

1 个答案:

答案 0 :(得分:3)

调整第5个变量并尝试以下代码:

Option Explicit
Sub test()

Application.DisplayAlerts = False
Dim wb As Workbook
Set wb = ThisWorkbook

'*******************************************
'Adapt this vars

Dim path_wbToOpen As String
Dim myRange As String
Dim sheet_opened As String
Dim ws_final As Worksheet
Dim lastRow As Integer

path_wbToOpen = "C:\test\test.xlsx" 'path of workbook where is the data
myRange = "A1:D1" 'Range to cpy
sheet_opened = "sheet_opened" 'name in opened WB where is sheet data
Set ws_final = wb.Sheets("sh_test") 'Sheet in current WB to paste data
lastRow = ws_final.Range("A" & Rows.Count).End(xlUp).Row + 1 ' set the last row (adapt column to check last row)


'*******************************************

'open another workbook from current one
Dim wbToOpen As Workbook
Set wbToOpen = Workbooks.Open(path_wbToOpen)

'Copy Data from opened WB
wbToOpen.Sheets(sheet_opened).Range(myRange).Copy 'Copy the data

'current WB
ws_final.Range("a" & lastRow).PasteSpecial ' past to the last row

'Clear Data and close WB
wbToOpen.Sheets(sheet_opened).Range(myRange).Clear 'Clear Data
wbToOpen.Close 'close WB

Application.DisplayAlerts = True

End Sub