Search code examples
vbaexcelcopycopy-paste

VBA - copy rows - if it found error, then continue in copy cells


I have macro which copy cells to below's cells.

Sub CopyRows2()

Dim LastRow As Long

With Worksheets("Ready to upload") ' <-- here should be the Sheet's name
    LastRow = .Cells(.Rows.Count, "AD").End(xlUp).Row ' last row in column C

For i = 2 To LastRow
If Range("AD" & i) > "" And Range("AD" & i + 1) = "" Then
    Range("AD" & i).Copy
    Range("AD" & i + 1).PasteSpecial xlPasteValues
    Application.CutCopyMode = False

Else

    End If
Next

End With

ActiveWindow.ScrollRow = 1 'scrolling the screen to the top

End Sub

It works fine, until it will found #N/A, then it will give me an error msg: Run-time error '13' - type mismatch. In that case, I would like to skip it and then continue in copy rows.

[enter image description here

Could you advise me, how to do that, please?

Many thanks!


Solution

  • Option 1

    The easiest way is to embed On Error Resume Next in your code. Then it will work.


    Option 2 If you want to be one step more professional, then you can use something like this:

    Sub CopyRows2()
    
        Dim LastRow As Long
    
        On Error Resume Next
    
        'your code
    
        If Err.Number = 13 Then Err.Clear
        On Error GoTo 0
    
    End Sub
    

    It will disregard error 13, but it will tell you if there are other errors, which is quite useful.


    Option 3 Check for error like this:

    If Not IsError(Range("AD" & i)) And Not IsError(Range("AD" & i + 1)) Then
        'embed the code here
    End If