VBA empty
In this article we will be talking about a method that let's you check whether a cell is empty. It also works for checking a range of cells. The method in VBA is the IsEmpty function and is one of the most commonly used functions to check for VBA empty cells. This function is one of the basics so you don't have to have any prior knowledge to understand the code we do here.
The IsEmpty function is being used in checking whether a cell is empty or has a text value. This function is similar to the IsBlank Function. The IsEmpty function in Visual Basic for Applications lets us know if the cell contains a values or is an empty cell. If the specific cell has nothing or is an empty cell, VBA can show a message to the user that the specific cell is empty or not.
We can now start our macro code.
Code:
Sub example1()
Dim AB As String
AB = IsEmpty(Range("D5").Value)
MsgBox AB
End Sub
Code explanation:
Dim AB As String
- we have set AB as our string variableAB = IsEmpty(Range("D5").Value)
- this refers to the value of our string variable which contains the range of the cell we wished to check and the .value for the method we are currently using.MsgBox AB
- this will instruct VBA to show the result in the message box.Let's take a look at the result after we have run the code:
Let's take a look at another example:
Code:
Sub example2()
If IsEmpty(Range("D5")) = False Then
MsgBox "Cell D5 has the text and not empty"
Else
MsgBox "Cell D5 do not have the text and is empty"
End If
End Sub
Code explanation:
If IsEmpty(Range("D5")) = False Then
- this defines the location of the cell we wished to work on.MsgBox "Cell D5 have the text and not empty"
- we are using the message box function and if the cell has a text value this message will appear in our message box.MsgBox "Cell D5 do not have the text and is empty"
- we are using the message box function, and if the cell does not have a text value, this message will appear in our message box.Let's take a look at the result after running the code:
Let's run the code again except this time with a value in cell D5:
The message in our message box changes because we have a text value in cell D5.
Note:
-IsEmpty is a function that we can use in a single or a range of cells.
In this article we showed you the IsEmpty method to check for a an empty cell or range of cells using VBA. We showed you how you might use this method in conjunction with an If statement to perform operations conditionally. We hope this article helped you solve the task at hand. Thanks for joining us!