问题:Worksheet类的粘贴方法失败

时间:2019-01-15 09:17:09

标签: excel vba

我一直在从事一项工作,旨在打开和复制一个工作表中的信息,然后将其复制到另一个工作表中。这是脚本

Sub Data_API()        
    Dim xlApp, xlBook        
    Dim xlBook2 As Workbook

    Set xlApp = CreateObject("Excel.Application")        
    Set xlBook = xlApp.Workbooks.Open("C:\Users\Pear\Book2.xlsm")        
    Set xlBook2 = Workbooks("Extract.xlsb")

    xlApp.Visible = True        
    xlApp.Run "ImportFile"

    xlBook.Worksheets("Sheet1").Range("A2:K500").Copy        
    xlBook2.Activate

    ActiveSheet.Paste Destination:=Worksheets("Data").Range("A2")

    xlBook.Application.CutCopyMode = False   
    xlBook.Close False

    Application.DisplayAlerts = False
End Sub

我收到如下错误消息:

  

运行时错误1004:工作表类的粘贴方法失败。

当我选择debug时,它会将我定向到这一行代码

ActiveSheet.Paste Destination:=Worksheets("Data").Range("A2")

任何想法/反馈/建议的更改将不胜感激。

1 个答案:

答案 0 :(得分:0)

请勿使用.Activate,请参见How to avoid using Select in Excel VBAActivate的技术是相同的。

代替在一条语句中复制,并指定在哪个工作簿Worksheets("Data")中:

xlBook.Worksheets("Sheet1").Range("A2:K500").Copy Destination:=xlBook2.Worksheets("Data").Range("A2")

此外,您无需打开另一个Excel实例。请尝试以下操作:

Sub Data_API()        
    Dim wbSrc As Workbook        
    Set wbSrc = Workbooks.Open("C:\Users\Pear\Book2.xlsm")        

    Dim wbDest As Workbook
    Set wbDest = Workbooks("Extract.xlsb") 'assumes Extract.xlsb is already open

    Application.Run "ImportFile"

    wbSrc.Worksheets("Sheet1").Range("A2:K500").Copy Destination:=wbDest.Worksheets("Data").Range("A2")

    Application.CutCopyMode = False   
    wbSrc.Close False

    'Application.DisplayAlerts = False 'why this here?
End Sub