'Run-time error '1004' when trying to copy a range (Excel VBA) [duplicate]
I am trying to copy a range of cells for which I don't know the last row and column (though I can easily get to those using variables). Unfortunately though, the way I am trying to reference a range is giving me a run-time error 1004 (Application-defined or object-defined error) when I use variables, and I can't figure out why. Below is a sample of the code:
Dim wkbk As Workbook
Dim copy_rng As Range
...
Set copy_rng = wkbk.Worksheets("Payable").Range("A1:Y3500")
Set copy_rng = wkbk.Worksheets("Payable").Range(Cells(1, 1), Cells(last_row_pay, last_col_pay))
The first Set statement is simply an example, and it works fine (so I know wkbk is properly defined and it's finding the "Payable" worksheet). Does anybody know why the second Set statement would not work? Is there a syntax issue? (During debug, if I hover over the last_row_pay and last_col_pay variables, I can see valid values--1533 and 25 respectively.) Thanks for any help.
Solution 1:[1]
If the range that you are trying to copy is a contiguous set of cells then I find the easiest way to get the size of the range without hard coding any row / column counts is to use CurrentRegion
Sub GetCurrentRange
Dim rng as range
Set rng = Worksheets("Payable").Range("A1").CurrentRegion
End Sub
The advantage here is that even if you add rows / columns to your dataset you don't need to bother working out the new column and row limits as CurrentRegion does this for you
Example:
A B C
1 10 20 30
2 40 50 60
3 70 80 90
Sub GetCurrentRange
Dim rng as range
Set rng = Worksheets("Payable").Range("A1").CurrentRegion
Debug.Print rng.Address //Prints $A$1:$C$3
End Sub
Solution 2:[2]
with Worksheets("Payable")
copy_rng = .Range(.Cells(1, 1), .Cells(last_row_pay, last_col_pay)).Value
end with
more lines, but work..
Solution 3:[3]
I had the same issues. You need to qualify both cell and range properties.
Set copy_rng = wkbk.Worksheets("Payable").Range(Cells(1, 1), wkbk.Sheets("Payable").Cells(last_row_pay, last_col_pay))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex P |
| Solution 2 | user2978925 |
| Solution 3 | bs0d |
