Home » excel » excel – Error while copying data from one sheet to another using vba

excel – Error while copying data from one sheet to another using vba

Posted by: admin May 14, 2020 Leave a comment

Questions:

While copying data from Sheet1 to Sheet2 I am getting

“Run-time error ‘1004’: Application-defined or object-defined error”

I am using vba code:

lnRow = 33
Sheets("Sheet1").Range("A3:C14").Copy Destination:=Sheets("Sheet2").Range(Cells(lnRow + 3, 1))

How can I copy data from Sheet1 to Sheet2 using column numbers?

How to&Answers:

Actually the problematic part is Sheets("Sheet2").Range(Cells(lnRow + 3, 1)) and there are 2 issues with it.

1. Issue

For the Cells object there is not specified in which worksheet it is so VBA assumes ActiveSheet. It is the same as writing Sheets("Sheet2").Range(ActiveSheet.Cells(lnRow + 3, 1)).

Now if the active sheet is not Sheet2 then the code will fail because the Range object is not in the same sheet as the Cells object, and that is not allowed.

2. Issue

According to the documentation of the Worksheet.Range property it accepts 2 arguments Range(Cell1, Cell2) where the second is optional, but only if the first is an address string.

Cell1

  • A String that is a range reference when one argument is used.
  • Either a String that is a range reference or a Range object when two arguments are used.

So that means you can use the following syntax:

  • Range("Address")
  • Range("Address", "Address")
  • Range(Cells(row, column), Cells(row, column))

but you cannot use

  • Range(Cells(row, column))

because if only one argument is used it must be a string/address. Actually the last one does not exist because you then can use Cells directly without using Range: Cells(row, column)


So in your case that means you must use Cells directly:

Sheets("Sheet2").Cells(lnRow + 3, 1)

Answer:

If you want to use the cells method then the error is due to the usage of range(cells(3,1)). Instead use sheets("Sheet1").range(cells(3,1),cells(4,1)). Otherwise you can omit the cells and specify the range as usual e.g. range("C4:D5").