简体   繁体   中英

Copying sheet to another workbook VBA

I am trying to copy one sheet to another workbook using VBA. However I receive an Application defined or object defined error, when it comes to the copy row.

Dim x As Workbook   

  Set x = Workbooks.Open("S:\INM\MME9EG\Zahlenwerk MMA2EG Equities\DHN\DHN_Europa.xls")

  x.Sheets("Bericht_799026").Range("B4:IV150000").Copy _
    ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IV150000").PasteSpecial

What's wrong with your formulation :

x.Sheets("Bericht_799026").Range("B4:IV150000").Copy _
ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IV150000").PasteSpecial

You are specifying a Destination for the Copy method by using _ and yet you use PasteSpecial so it isn't a Range anymore, thus the error!

Also, you are opening an .xls file, which is the old Excel format and only contains 65,536 rows and you are trying to copy 150,000!

See : https://superuser.com/a/366473/505550


A lot of ways to do this :

If you specify the output size, you'll have to be accurate so that input and output size are the same :

x.Sheets("Bericht_799026").Range("B4:IV65536").Copy
ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IU65533").PasteSpecial

or

x.Sheets("Bericht_799026").Range("B4:IV65536").Copy _
    ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IU65533")

Or you could just specify the 1st cells in which you want to paste :

x.Sheets("Bericht_799026").Range("B4:IV65536").Copy
ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IU65533").PasteSpecial

or

x.Sheets("Bericht_799026").Range("B4:IV65536").Copy _
    ThisWorkbook.Sheets("DHN Europe 799026").Range("A1")

Or the best way for the end :
you'll have to be accurate but it is much much faster for transfering data (and data only!)):

ThisWorkbook.Sheets("DHN Europe 799026").Range("A1:IU65533").Value = _
x.Sheets("Bericht_799026").Range("B4:IV65536").Value

not to bother about matching source and destination ranges sizes

With x.Sheets("Bericht_799026").Range("B4:IV150000")
    .Value = ThisWorkbook.Sheets("DHN Europe 799026").Range("A1").Resize(.Rows.Count, .Columns.Count).Value
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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