How can I open a workbook, copy data, and add to last line on another workbook? [closed]

空扰寡人 提交于 2019-12-13 16:34:10

问题


Is it possible to open another workbook from the current one and copy the data on the table columns and paste on the last line of the table in the current workbook? And also delete the source data.


回答1:


Adapt the 5th vars and try this code :

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


来源:https://stackoverflow.com/questions/50693655/how-can-i-open-a-workbook-copy-data-and-add-to-last-line-on-another-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!