VBA if vlookup value found #N/A in any row then code should be stop

negi

Board Regular
Joined
Apr 16, 2009
Messages
87
Hi All,
I'm trying , if vlookup value found #N/A in any row then code should be stop and display msg with error row number.




Sub nam()
Dim x As Long

x = Range("g" & Rows.Count).End(xlUp).Row


Range("N2:N" & x).FormulaR1C1 = "=VLOOKUP(RC[-7],br_name,3,0)"

End Sub
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
When you apply that formula to a whole range like that, there is really no way to "stop" when it finds an error since you are doing the whole range at once.
However, we can loop through the range after that and look for errors, i.e.
VBA Code:
    Dim r As Long
    For r = 2 To x
        If IsError(Cells(r, "N")) Then
            MsgBox "Error on row " & r
            Exit Sub
        End If
    Next r

If you want to check each one as it is being created, you will need to add the formula assignment into the loop so you are populating one row at a time, i.e.
VBA Code:
Sub nam()

    Dim x As Long
    Dim r As Long

    x = Range("g" & Rows.Count).End(xlUp).Row
    
    For r = 2 To x
        Cells(r, "N").FormulaR1C1 = "=VLOOKUP(RC[-7],br_name,3,0)"
        If IsError(Cells(r, "N")) Then
            MsgBox "Error on row " & r
            Exit Sub
        End If
    Next r

End Sub
Note that using loops may slow your code down if you have a lot of rows you are looping through, but I think that is the price you have to pay if you want it to return the error and stop at that line of code without finishing the rest.
 
Upvote 0

Forum statistics

Threads
1,215,025
Messages
6,122,734
Members
449,094
Latest member
dsharae57

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top