When using Range.SpecialCells with a range that doesn't contain cells that match the criteria an error is thrown saying that no cells were found.
The most common solution to this issue is letting it happen and using an error handler to deal with it.
Is that the best known way to solve it or is there other solutions that might be as good or better which avoid using an error handler?
The only thing I can think of would be saving the first cell's value, then changing its value to one that matches the criteria so it avoids the error making it always match at least that one cell, then change the value back to its original value and check the matched range's address to see if it matched that one cell only or more.
A bad/slow solution would be to not make use of it at all and just use loops with checks.
Here's some simple sample code to demostrate a little how it works with the error handler:
Private Sub Procedure()
Dim OriginalRange As Excel.Range
Dim NewRange As Excel.Range
Set OriginalRange = ThisWorkbook.Worksheets(1).Range("A1:C4")
On Error GoTo ErrorHandler
Set NewRange = OriginalRange.SpecialCells(Type:=Excel.XlCellType.xlCellTypeConstants, Value:=Excel.XlSpecialCellsValue.xlNumbers)
Exit Sub
ErrorHandler:
If (VBA.Err.Number <> 1004) Then VBA.Err.Raise VBA.Err.Number
End Sub
Yes it is perfectly normal (I prefer this way) to use the error handler. What I do is, I sandwhich it between On Error Resume Next
and On Error GoTo 0
and then check If NewRange is Nothing
See this example
On Error Resume Next
Set NewRange = OriginalRange.SpecialCells(Type:=Excel.XlCellType.xlCellTypeConstants, _
Value:=Excel.XlSpecialCellsValue.xlNumbers)
On Error GoTo 0
If NewRange Is Nothing Then
MsgBox "Your message here informing the USER that desired cells were not found"
Else
'
'~~> Do whatever you want with the range
'
End If
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.