简体   繁体   English

使用VBA宏从另一个Excel文件复制数据

[英]Copy data from another Excel file with VBA macro

I would like to open a workbook and copy from the opened workbooks sheet to my worbook sheet like that: 我想打开一个工作簿,并从打开的工作簿表复制到我的工作簿表,如下所示:

Private Sub Workbook_Open()
    Dim openedFile As String
    Dim sourcebook As Workbook
    openedFile = Application.GetOpenFilename(fileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") 'Source book opening

    Set sourcebook = Workbooks.Open(openedFile)

    Application.CutCopyMode = True
    sourcebook.Worksheets("source_sheet").Range("A1:L100").Copy
    ThisWorkbook.Worksheets("dest_sgheet").Range("A1").PasteSpecial Paste:=xlPasteValues
    Application.CutCopyMode = False
    Call sourcebook.Close(False)
End Sub

I got this error message after I runing this code: 我运行以下代码后收到以下错误消息:

Run-time error '1004": PasteSpecial method of Range class failed 运行时错误'1004”:Range类的PasteSpecial方法失败

It's occour at this line: 这条线是黑色的:

ThisWorkbook.Worksheets("dest_sheet").Range("A1").PasteSpecial Paste:=xlPasteValues

try activating the workbook first ("This workbook") and then activating the sheet where you'd like to paste the data. 尝试先激活工作簿(“此工作簿”),然后再激活要粘贴数据的工作表。 The error tends to occur because either the range is not visible nor in existence. 由于范围不可见或不存在,因此容易发生错误。

Your code should work . 您的代码应该可以工作。 change this line: 更改此行:

ThisWorkbook.Worksheets("dest_sgheet").Range("A1").PasteSpecial Paste:=xlPasteValues

with this one: 与此:

 ThisWorkbook.Worksheets("dest_sheet").Range("A1").PasteSpecial Paste:=xlPasteValues

EDIT Based on OP comments on 25-05-2016 I have re-run the program as per OP code after correcting minor typo error in sheet spelling. 编辑基于2016年5月25日的OP注释,我在纠正了表拼写中的轻微错字错误后,根据OP代码重新运行了该程序。 Program runs successfully without any problem. 程序成功运行,没有任何问题。 I am not getting Run time error 1004. Screenshot shows that data is getting copied properly. 我没有收到运行时错误1004。屏幕快照显示数据正在正确复制。

屏幕截图显示了输入和输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM