Home » excel » excel – Display cell address and message box on error and exit the Macro, if not, continue

excel – Display cell address and message box on error and exit the Macro, if not, continue

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to first check my Range for #NA errors and then display the cell addresses containing the error before quitting the Macro. This is what I’ve done so far.

Now, if there are errors present, I’d like to display a MsgBox warning the user of the error and stop the rest of the program from executing, if however there are none then I’d like for it to move on to the rest of the program

Check for NA error:

For Each c In myRange

    If IsError(c) = True Then

        Debug.Print c.Address

    End If

Next c

MsgBox "Check for errors and run gain"

Exit Sub

'continuation of the program
How to&Answers:

This one will write all the addresses of the errors in a string and will display them after the code runs:

Sub TestMe()

    Dim myRange As Range
    Dim myCell As Range
    Dim errorList As String

    Set myRange = Worksheets(1).Range("A1:C10")

    For Each myCell In myRange
        If IsError(myCell) Then
            errorList = errorList & vbCrLf & myCell.Address
        End If
    Next

    If Len(errorList) > 0 Then
        MsgBox errorList
        Exit Sub
    End If

End Sub

AFter the loop, there is a check for the 1Len(errorList) and if it is bigger than 0, it shows the MsgBox and exits the sub.

enter image description here

Answer:

I think this will do the trick:

Dim errorArray()
Dim i As Integer
Dim checkArray As Integer
Dim errorString As String

For Each c In myRange
    If IsError(c) = True Then
        ReDim Preserve errorArray(i)
        errorArray(i) = c.Address
        i = i + 1
    End If
Next c

On Error Resume Next
checkArray = UBound(errorArray)

If Err = 0 Then
    errorString = "An error(s) occured in following cell(s):" & Chr(10)
    For i = 0 To UBound(errorArray)
        errorString = errorString & errorArray(i) & Chr(10)
    Next

    MsgBox errorString

    Exit Sub

End If

Err.Clear
On Error GoTo 0

Answer:

As per my comment you could also try to use SpecialCells to avoid any iteration:

Sub test()

Dim rng As Range

With Sheet1 'Change according to your sheets CodeName

    'Setup your range to check for errors
    Set rng = .Range("A1:C4")

    'Check if any errors exist and act if they do
    If .Evaluate("SUM(IF(ISERROR(" & rng.Address & "),1))") > 0 Then
        MsgBox "Still errors in " & rng.SpecialCells(-4123, 16).Address(False, False)
        Exit Sub
    End If

End With

End Sub

If your cells are not the result of formulas but constants instead, please change SpecialCells(-4123, 16) to SpecialCells(2, 16).