将值从一个Excel工作簿复制并粘贴到另一个工作簿

时间:2017-08-18 17:13:31

标签: excel excel-vba copy-paste vba

我尝试记录一个将一个工作簿的值粘贴到另一个工作簿的宏,但是当我这样做时,我得到一个“运行时错误9下标超出范围”

我确信这只是一个简单的修复,我是宏的新手,所以任何帮助都将不胜感激。这是我的代码:

`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

1 个答案:

答案 0 :(得分:1)

通常更好的做法是远离激活和选择。

'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