使用.PasteSpecial运行时错误'438'

时间:2013-10-16 12:02:25

标签: vba excel-vba excel

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

提前谢谢!

1 个答案:

答案 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