简体   繁体   中英

Copy and Paste values from one excel workbook to another

I tried to record a macro that pasted the values of one workbook into another workbook, however when I do this I get a "run-time error 9 subscript out of range"

I am sure this is just an easy fix, and I am new to macros, so any help would be appreciated. Here is my code:

`Sub Refresh()
'
' Refresh Macro
' Update XY Act. Values 2017
'
' Keyboard Shortcut: Ctrl+r
'
Windows("XY Update File v2.xlsx").Activate
Selection.Copy
Windows("Engineering XY Chart v2.xlsx").Activate
ActiveSheet.Paste
End Sub

Its generally better practice to stay away from Activate and Select.

'variables
Dim workbook1 As Workbookm, workbook2 As Workbook, filePath1 As String

filePath1 = ThisWorkbook.Path & "\Engineering XY Chart v2.xlsx" 'assuming filepath is the same as macro workbook
filePath2 = ThisWorkbook.Path & "\XY Update File v2.xlsx" 'assuming filepath is the same as macro workbook

'make references to workbooks
Set workbook1 = Workbook.Open(Filename:=filePath1)
Set workbook2 = Workbook.Open(Filename:=filePath2)

'Copies cell A1 from sheet1 of workbook 2 to cell A1 sheet 1 of workbook 1
workbook1.Sheets(1).Range("A1").Value = workbook2.Sheets(1).Range("A1").Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM