How to test or check cell content
When you work with VBA (macros) in Excel, you often need to test or check cell content. Is the cell empty, is it a number, a text (string), a formula, an error, a date - or does it have a comment or conditional formatting?
And how do you do that?
Below are some examples. If you mark the code with the mouse, you can copy (CTRL+C) and paste (CTRL+V) it into a VBA module. The examples use cell A1 in the active sheet, but any cell or larger range can be used.
If you are viewing this page with a device with a small screen, some of the code lines may appear broken/wrapped, but they will be okay, once you paste them into a VBA module.
Sub CellCheck()
Dim rCell As Range
Dim sMyString As String
On Error GoTo ErrorHandle
Set rCell = Range("A1")
If Len(rCell.Formula) = 0 Then
MsgBox "Cell " & rCell.Address & " is empty."
End If
If IsEmpty(rCell) Then
MsgBox "Cell " & rCell.Address & " is empty."
End If
If IsNumeric(rCell.Value) Then
MsgBox "Cell " & rCell.Address & " is a numeric value."
End If
If IsError(rCell.Value) Then
MsgBox "Cell " & rCell.Address & " contains an error."
End If
If IsDate(rCell.Value) Then
MsgBox "Cell " & rCell.Address & " is a date."
End If
If IsNumeric(rCell.Value) = False And _
IsError(rCell.Value) = False Then
sMyString = Trim(rCell.Value)
If Len(sMyString) > 0 Then
MsgBox "Cell " & rCell.Address & " is a text with " & _
Len(sMyString) & " characters."
Else
MsgBox "The cell contains blanks only"
End If
End If
If rCell.FormatConditions.Count > 0 Then
MsgBox rCell.Address & " has conditional formatting."
Else
MsgBox "No conditional formatting."
End If
If rCell.HasFormula Then
MsgBox "Cell " & rCell.Address & " contains a formula."
Else
MsgBox "The cell has no formula."
End If
If rCell.Comment Is Nothing Then
With rCell.AddComment
.Visible = False
.Text "Comment added " & Date
End With
Else
MsgBox rCell.Address & " has a comment."
End If
BeforeExit:
Set rCell = Nothing
Exit Sub
ErrorHandle:
MsgBox Err.Description & " Error in procedure CellCheck."
Resume BeforeExit
End Sub
About cells
In the examples above I have written "rCell.Value" many times. Strictly speaking that is not necessary, because "Value" is a cell's default property, so I could have achieved the same just be writing "rCell".
However I find that a bit sloppy, and it also makes it more difficult to read.
Related:
|