RedditPP Mascot

RedditPP

r/vba • … • u/Aeliandil

Application/object-defined error with a .Range(Cells(),Cells()) in Excel

Hello everyone,

Apologies as this is likely a question and issue that has been asked countless time, but I was not able to find a working solution.

I'm writing an Excel macro which would basically copy any extra columns in one worksheet to another, and expand it down. Now here is my code:

Sub UpdateQuery()

Dim wb As Workbook Dim ws As Worksheet, wsSrc As Worksheet, wsUpdt As Worksheet Dim LColSrc, LColUpdt, LRowSrc, LRowUpdt As Long

Set wb = ActiveWorkbook Set wsSrc = wb.ActiveSheet On Error GoTo WsError Set wsUpdt = wb.Worksheets("Data") On Error GoTo 0

LColSrc = wsSrc.Cells(2, Columns.Count).End(xlToLeft).Column LColUpdt = wsUpdt.Cells(2, Columns.Count).End(xlToLeft).Column LRowSrc = wsSrc.Range("A" & Rows.Count).End(xlUp).Row LRowUpdt = wsUpdt.Range("A" & Rows.Count).End(xlUp).Row

'Check if there are extra columns, copy extra columns, first 2 rows, in the original tab, paste in the new tab. 'Take extra columns 2nd row, copy/paste it to the end of new tab If LColUpdt = LColSrc Then Else wsSrc.Range(Cells(1, LColUpdt + 1), Cells(2, LColSrc)).Copy Destination:=wsUpdt.Cells(1, LColUpdt + 1) Range(wsUpdt.Cells(2, LColUpdt + 1), wsUpdt.Cells(2, LColUpdt + 1).End(xlToRight)).AutoFill _ Destination:=wsUpdt.Range(Cells(2, LColUpdt + 1), Cells(LColSrc, LRowUpdt)) End If

End Sub

To simplify it, in one example, the macro will copy ActiveSheet!M1:X2 (which are the extra columns (headers + first formula row) that Data doesn't have), paste it in Data!M1:X2, then copy Data!M2:X2 (formula row) and expand it down until the last row.

Now, my issue is with `Destination:=wsUpdt.Range(Cells(2, LColUpdt + 1), Cells(LColSrc, LRowUpdt))` and specifically `Cells(LColSrc, LRowUpdt)` where it is giving me a "Application-defined or object-defined error". Now, most other threads and websites say the issue is due to unqualified cells, but putting wsUpdt.Cells(LColSrc, LRowUpdt) doesn't change anything.

Any idea on what I am doing wrong?

P.S.: the full macro is a longer than that as it is doing other operations afterwards (renaming worksheets, looping into pivot table data source, ...), but I don't believe it to be relevant with my issue and didn't want to crowd the thread.

Edit: more precision, when watching LColSrc and LRowUpdt are correctly calculated as 24 and 19258 - which give X19258 (should give) - but somehow, Cells(LColSrc, LRowUpdt) throws out an error.

— 0