我正在尝试创建一个简单的宏来将数据从已关闭的Excel文件复制到我打开的当前文件中。到目前为止,我已经创建了这个
Sub CopyData()
Dim path As String
path = "C:\Users\sam\Coding\bk.xlsx"
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim openWb As Workbook
Set openWb = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWb.Sheets("Sheet1")
currentWb.Activate
openWb.Activate
openWs.Range("A1:C2").Copy
currentWb.Range("A1").PasteSpecial
openWb.Close (False)
End Sub
但是我得到一个运行时错误438,并在调试时突出显示行“currentWb.Range(”A1“)。PasteSpecial”。我到处寻找答案,但我没有成功。我的问题是,我错过了什么?
提前谢谢!
答案 0 :(得分:1)
问题是
currentWb.Range("A1").PasteSpecial
应该是
currentWb.Sheets("SomeSheet").Range("A1").PasteSpecial xlPasteAll
用您尝试的任何内容替换xlPasteAll
。
Range
对象不是Workbook
的一部分,而是Worksheet
此外,您无需使用.Activate
。您的代码可以写成
Sub CopyData()
Dim path As String
Dim currentWb As Workbook, openWb As Workbook
Dim currentWs As Worksheet, openWs As Worksheet
path = "C:\Users\sam\Coding\bk.xlsx"
Set currentWb = ThisWorkbook
'~~> Change this applicable
Set currentWs = currentWb.Sheets("Sheet1")
Set openWb = Workbooks.Open(path)
Set openWs = openWb.Sheets("Sheet1")
openWs.Range("A1:C2").Copy
currentWs.Range("A1").PasteSpecial xlPasteValues
openWb.Close (False)
End Sub