1

我正在尝试创建一个简单的宏来将数据从关闭的 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”。我到处搜索以找到答案,但我没有成功。我的问题是,我错过了什么?

先感谢您!

4

1 回答 1

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
于 2013-10-16T12:27:25.750 回答