top of page

You are learning Error Handling in MS Excel

How to use the CELL function (VBA) to retrieve error information about a specific cell?

The CELL function in VBA isn't specifically designed to retrieve error information about a cell. However, you can combine it with other functions and properties to achieve this. Here are two approaches:

1. Using IsError and Text:

```vba
Function GetCellError(cellRef As Range) As String
' Check if cell contains an error
If IsError(cellRef.Value) Then
' Return the specific error type as text
GetCellError = cellRef.Value ' Will return the error value (#VALUE!, #NAME!, etc.)
Else
GetCellError = "" ' No error present
End If
End Function
```

Explanation:

- This function takes a `cellRef` argument specifying the cell you want to check.
- It uses `IsError(cellRef.Value)` to see if the cell's value is an error.
- If there's an error, the function directly returns the error value itself (e.g., "#VALUE!").
- If no error exists, an empty string ("") is returned.

2. Using .FormulaLocal property and InStr:

```vba
Function GetCellError(cellRef As Range) As String
Dim formula As String

' Check if the cell has a formula
If Len(cellRef.FormulaLocal) > 0 Then
formula = cellRef.FormulaLocal ' Get the formula
' Look for any error indicator string within the formula
If InStr(formula, "#VALUE!") > 0 Then
GetCellError = "#VALUE!"
ElseIf InStr(formula, "#NAME!") > 0 Then
GetCellError = "#NAME!"
End If
' You can add checks for other error indicators here
Else
GetCellError = "" ' No formula, no error assumed
End If
End Function
```

Explanation:

- This function also takes a `cellRef` argument.
- It checks if the cell has a formula using `Len(cellRef.FormulaLocal) > 0`.
- If there's a formula, it retrieves it with `cellRef.FormulaLocal`.
- The function then uses `InStr` to search for specific error indicator strings (#VALUE!, #NAME!) within the formula.
- If a match is found, the corresponding error type is returned.
- You can add checks for other error indicators within the `ElseIf` block.
- If there's no formula, the function assumes no error and returns an empty string.

Important Notes:

- These functions provide basic error information. For more detailed analysis, consider using error handling within your VBA code.
- The second approach might not be suitable for complex formulas with nested functions, as it only searches for specific error strings.
- Remember to adjust the error checks in both functions based on the specific errors you're interested in.

bottom of page