Question

I have two workbooks. They are both open. Book1.xls and Book2.xlsm. In each of those workbooks I have different worksheets:

Book1.xls -> A1, A2, A3

Book2.xlsm -> B1, B2, B3

I want to copy a specific cell range (B5:I29) from Book1.A1 to Book2.B2 (or any other sheets).

I seem to hit a hardwall with the understanding of the syntax and correct procedure to follow.

I tried:

' Set paths
FileToCopyFrom = "C:\Book1.xls"  'change path as required
FileToCopyTo = "C:\Book2.xlsm"         'change path as required

' Set Workbooks
Dim workbookToCopyFrom As Workbook
Set workbookToCopyFrom = Workbooks(FileToCopyFrom)
Dim workbookToCopyTo As Workbook
Set workbookToCopyTo = Workbooks(FileToCopyTo)

' Copy+paste
workbookToCopyFrom.sheet("A1")Range("B5:B29, I5:I29").Copy
Worksheets("B1").Range("A10").PasteSpecial (xlPasteValues)

But I am unable to make it happen. Can you please explain me the right procedure to set the workbooks, worksheets, cell range, copy and paste?

Thank you

Was it helpful?

Solution

Couple of errors.

If the workbooks are opened then simply change

Set workbookToCopyFrom = Workbooks(FileToCopyFrom)

to

Set workbookToCopyFrom = Workbooks("Book1.xls")

Similarly for the other

Set workbookToCopyTo = Workbooks("Book2.xlsm")

Also you are missing a DOT before the range object and a S in the Sheet object.

workbookToCopyFrom.sheet("A1")Range("B5:B29, I5:I29").Copy

needs to be

workbookToCopyFrom.Sheets("A1").Range("B5:B29, I5:I29").Copy

Next, your destination is incorrectly coded. I guess you wanted to do this?

workbookToCopyFrom.Sheets("A1").Range("B5:B29, I5:I29").Copy
workbookToCopyTo .Sheets("B1").Range("A10").PasteSpecial(xlPasteValues)

So your final code will look like this

Dim workbookToCopyFrom As Workbook
Dim workbookToCopyTo As Workbook

Set workbookToCopyFrom = Workbooks("Book1.xls")

Set workbookToCopyTo = Workbooks("Book2.xlsm")

' Copy+paste
workbookToCopyFrom.Sheets("A1").Range("B5:B29, I5:I29").Copy
workbookToCopyTo.Sheets("B1").Range("A10").PasteSpecial(xlPasteValues)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top