Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Runtime Error trying to copy to a variable cell – it works if I use .End(xlUp), why is .End(xlRight) a problem?

I have multiple reports that are pulling the same data. I’m trying to flag these duplicates by copying an identifier at the end of the first iteration of that data. Currently my code reads as follows:

        Set OppID = OwnerName.Offset(0, -3)
        Set CurrentWS = Worksheets(OwnerName.Value)
        Set OppIDField = CurrentWS.Range("C1", Range("C1").End(xlDown))
        
        IDCount = WorksheetFunction.CountIf(OppIDField, OppID)
        
        If IDCount > 0 Then
            
            Set Existing = OppIDField.Find(OppID)
            Debug.Print Existing.Address
        
            
            OwnerName.Offset(0, -5).Copy Destination:=Worksheets(OwnerName.Value).Range(Existing.Address).End(xlRight).Offset(0, 1)

Running the code as-is gives me a runtime error in the Copy section.

If I change "xlRight" to "xlUp" it will copy the correct data into the wrong place, but it at least won’t experience the runtime error and will complete the macro.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The offset is to put it into the next cell over from the last one with data. Is there a reason why xlRight would cause an error that xlUp wouldn’t?

>Solution :

The XlDirection (the argument of End method) value must be one of the following: xlDown, xlToLeft, xlToRight, or xlUp. End(xlRight) causes the runtime error (1004).

Microsoft documentation:

XlDirection enumeration (Excel)

If the variable Existing refers to the last used cell in the row, End(xlToRight) will reach the last column in that row. Using Offset(0, 1) will exceed the sheet limit, which causes the runtime error (1004) too.

Microsoft documentation:

Range.End property (Excel)

Try locating the destination cell using End(xlToLeft). If this doesn’t match your expected output, please share the desired cell location.

With Worksheets(OwnerName.Value)
    OwnerName.Offset(0, -5).Copy Destination:=.Cells(Existing.Row, .Columns.Count).End(xlToLeft).Offset(0, 1)
End With
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading