How to check the cell is valid or not in VBA?
excel, vba
Solution
- Use a `Range` object to test whether it is valid (preferred for versatility)
- Test whether the column is valid (assumes hard-code of your `OFFSET` as `(0,2)`
(1) code
Sub Test1()
Dim r As Long
Dim c As Long
r = 1
c = 1
Dim rng1 As Range
On Error Resume Next
Set rng1 = Cells(r, c).Offset(0, -2)
On Error GoTo 0
If Not rng1 Is Nothing Then
'proceed with your code - range exists
Else
MsgBox "Range Error", vbCritical
End If
End Sub
(2) code
Sub Test2()
Dim rng1 As Range
Dim r As Long
Dim c As Long
c = 3
r = 1
If c - 2 <= 0 Then
MsgBox "Error", vbCritical
Else
Set rng1 = Cells(r, c).Offset(0, -2)
End If
End Sub
Problem
If - `r = 1`, and - `c = 1` the intended code below is invalid (it tries to return a cell two columns to the left of Column `A`) ``` Cells(r, c).Offset(0, -2) ``` How do I check whether the intended cell is valid or not in vba?