How do I express the condition «if value is not empty» in the VBA language? Is it something like this?
"if value is not empty then..."
Edit/Delete Message
Teamothy
1,9903 gold badges15 silver badges24 bronze badges
asked Dec 31, 2009 at 2:27
3
Use Not IsEmpty()
.
For example:
Sub DoStuffIfNotEmpty()
If Not IsEmpty(ActiveCell.Value) Then
MsgBox "I'm not empty!"
End If
End Sub
answered May 20, 2012 at 16:31
Jon CrowellJon Crowell
21.5k14 gold badges88 silver badges110 bronze badges
0
It depends on what you want to test:
- for a string, you can use
If strName = vbNullString
orIF strName = ""
orLen(strName) = 0
(last one being supposedly faster) - for an object, you can use
If myObject is Nothing
- for a recordset field, you could use
If isnull(rs!myField)
- for an Excel cell, you could use
If range("B3") = ""
orIsEmpty(myRange)
Extended discussion available here (for Access, but most of it works for Excel as well).
answered Jan 5, 2010 at 22:52
iDevlopiDevlop
24.6k11 gold badges89 silver badges147 bronze badges
2
Try this:
If Len(vValue & vbNullString) > 0 Then
' we have a non-Null and non-empty String value
doSomething()
Else
' We have a Null or empty string value
doSomethingElse()
End If
captainpete
6,1323 gold badges27 silver badges26 bronze badges
answered Dec 31, 2009 at 3:09
alejofvalejofv
4012 silver badges6 bronze badges
Why not just use the built-in Format() function?
Dim vTest As Variant
vTest = Empty ' or vTest = null or vTest = ""
If Format(vTest) = vbNullString Then
doSomethingWhenEmpty()
Else
doSomethingElse()
End If
Format() will catch empty variants as well as null ones and transforms them in strings.
I use it for things like null/empty validations and to check if an item has been selected in a combobox.
answered Jan 6, 2010 at 12:59
MarcandMarcand
3142 silver badges3 bronze badges
I am not sure if this is what you are looking for
if var<>"" then
dosomething
or
if isempty(thisworkbook.sheets("sheet1").range("a1").value)= false then
the ISEMPTY function can be used as well
answered Dec 31, 2009 at 4:38
AnthonyAnthony
8933 gold badges23 silver badges32 bronze badges
Alexphi’s suggestion is good. You can also hard code this by first creating a variable as a Variant
and then assigning it to Empty
. Then do an if/then with to possibly fill it. If it gets filled, it’s not empty, if it doesn’t, it remains empty. You check this then with IsEmpty
.
Sub TestforEmpty()
Dim dt As Variant
dt = Empty
Dim today As Date
today = Date
If today = Date Then
dt = today
End If
If IsEmpty(dt) Then
MsgBox "It not is today"
Else
MsgBox "It is today"
End If
End Sub
answered Dec 31, 2009 at 15:32
Todd MainTodd Main
28.9k11 gold badges82 silver badges146 bronze badges
You can use inputbox
function in a for loop:
Sub fillEmptyCells()
Dim r As Range
Set r = Selection
For i = 1 To r.Rows.Count
For j = 1 To r.Columns.Count
If Cells(i, j).Value = "" Then
Cells(i, j).Select
Cells(i, j).Value = InputBox( _
"set value of cell at column " & Cells(1, j).Value & _
" and row " & Cells(i, 1))
End If
Next j
Next i
End Sub
Toni
1,5354 gold badges15 silver badges23 bronze badges
answered Oct 28, 2021 at 8:02
I think the solution of this issue can be some how easier than we imagine. I have simply used the expression Not Null
and it worked fine.
Browser("micclass").Page("micclass").WebElement("Test").CheckProperty "innertext", Not Null
answered Aug 10, 2020 at 17:16
1
Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.
Проверка переменных и выражений
Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.
Синтаксис функций для проверки переменных и выражений:
Expression — выражение, переменная или необязательный аргумент для IsMissing.
Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.
Функция IsArray
Описание функции
Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:
- True — переменная является массивом;
- False — переменная не является массивом.
Пример с IsArray
Sub Primer1() Dim arr1(), arr2(1 To 10), arr3 Debug.Print IsArray(arr1) ‘Результат: True Debug.Print IsArray(arr2) ‘Результат: True Debug.Print IsArray(arr3) ‘Результат: False arr3 = Array(1, 2, 3, 4, 5) Debug.Print IsArray(arr3) ‘Результат: True End Sub |
Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.
Функция IsDate
Описание функции
Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:
- True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
- False — в иных случаях.
Пример с IsDate
Sub Primer2() Dim d1 As String, d2 As Date Debug.Print IsDate(d1) ‘Результат: False Debug.Print IsDate(d2) ‘Результат: True d1 = «14.01.2023» Debug.Print IsDate(d1) ‘Результат: True Debug.Print IsDate(Now) ‘Результат: True End Sub |
Функция IsEmpty
Описание функции
Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:
- True — переменная содержит значение Empty;
- False — переменной присвоено значение, отличное от Empty.
Пример с IsEmpty
Sub Primer3() Dim s As String, v As Variant Debug.Print IsEmpty(s) ‘Результат: False Debug.Print IsEmpty(v) ‘Результат: True v = 125 Debug.Print IsEmpty(v) ‘Результат: False Range(«A1»).Clear Debug.Print IsEmpty(Range(«A1»)) ‘Результат: True Range(«A1») = 123 Debug.Print IsEmpty(Range(«A1»)) ‘Результат: False End Sub |
Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).
Функция IsError
Описание функции
Функция IsError возвращает логическое значение, указывающее, является ли аргумент функции значением ошибки, определенной пользователем:
- True — аргумент функции является значением ошибки, определенной пользователем;
- False — в иных случаях.
Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.
Пример с IsError
Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:
Function Vkuba(x) If IsNumeric(x) Then Vkuba = x ^ 3 Else Vkuba = CVErr(25) End If End Function Sub Primer4() Debug.Print Vkuba(5) ‘Результат: 125 Debug.Print IsError(Vkuba(5)) ‘Результат: False Debug.Print Vkuba(«пять») ‘Результат: Error 25 Debug.Print IsError(Vkuba(«пять»)) ‘Результат: True End Sub |
Функция IsMissing
Описание функции
Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:
- True — если в процедуру не было передано значение для необязательного аргумента;
- False — значение для необязательного аргумента было передано в процедуру.
Пример с IsMissing
Function Scepka(x, Optional y) If Not IsMissing(y) Then Scepka = x & y Else Scepka = x & » (а необязательный аргумент не подставлен)» End If End Function Sub Primer5() Debug.Print Scepka(«Тропинка», » в лесу») ‘Результат: Тропинка в лесу Debug.Print Scepka(«Тропинка») ‘Результат: Тропинка (а необязательный аргумент не подставлен) End Sub |
Функция IsNull
Описание функции
Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:
- True — значением переменной или выражения является Null;
- False — в иных случаях.
Пример с IsNull
Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:
Sub Primer6() Dim Var Var = Null If Var = Null Then Debug.Print Var ‘Результат: «» If Var <> Null Then Debug.Print Var ‘Результат: «» If IsNull(Var) Then Debug.Print Var ‘Результат: Null End Sub |
Функция IsNumeric
Описание функции
Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:
- True — если аргумент функции может рассматриваться как число;
- False — в иных случаях.
Пример с IsNumeric
Sub Primer7() Debug.Print IsNumeric(«3,14») ‘Результат: True Debug.Print IsNumeric(«четыре») ‘Результат: False End Sub |
Функция IsObject
Описание функции
Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:
- True — переменная содержит ссылку на объект или значение Nothing;
- False — в иных случаях.
Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.
Пример с IsObject
Sub Primer8() Dim myObj As Object, myVar As Variant Debug.Print IsObject(myObj) ‘Результат: True Debug.Print IsObject(myVar) ‘Результат: False Set myVar = ActiveSheet Debug.Print IsObject(myVar) ‘Результат: True End Sub |
Home / VBA / VBA Check IF a Cell is Empty + Multiple Cells
To check if a cell is empty you can use VBA’s ISEMPTY function. In this function, you need to use the range object to specify the cell that you want to check, and it returns true if that cell is empty, otherwise false. You can use a message box or use a cell to get the result.
- Start with the function name “IsEmpty”.
- Specify the cell that you want to check.
- Use a message box or a cell to get the result value.
- In the end, run the code.
MsgBox IsEmpty(Range("A1"))
Check IF Multiple Cells Empty
If you want to check and count the empty cells from a range when you need to loop through each cell in the range.
Sub vba_check_empty_cells()
Dim i As Long
Dim c As Long
Dim myRange As Range
Dim myCell As Range
Set myRange = Range("A1:A10")
For Each myCell In myRange
c = c + 1
If IsEmpty(myCell) Then
i = i + 1
End If
Next myCell
MsgBox _
"There are total " & i & " empty cell(s) out of " & c & "."
End Sub
The above code loops through each cell in the range A1:A10 and check each cell one by one using the ISEMPTY function if it’s empty or not.
And for each empty cell it takes a count, and in the end, shows a message box with the total number of cells and empty cells out of that.
Use the following code if you want to highlight empty cells as well.
Dim i As Long
Dim c As Long
Dim myRange As Range
Dim myCell As Range
Set myRange = Range("A1:A10")
For Each myCell In myRange '
c = c + 1
If IsEmpty(myCell) Then
myCell.Interior.Color = RGB(255, 87, 87)
i = i + 1
End If
Next myCell
MsgBox _
"There are total " & i & " empty cell(s) out of " & c & "."
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
In this VBA Tutorial, you learn how to check if a cell or range is empty.
This VBA Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- Learn about commonly-used VBA terms here.
- Learn about the Excel Object Model and how to refer to objects here.
- Learn how to create references to cell ranges here.
- Learn how to declare and work with variables here.
- Learn about data types here.
- Learn how to work with worksheet functions within VBA here.
You can find additional VBA and Macro Tutorials in the Archives.
VBA Code to Check if Cell is Empty
To check if a cell is empty with VBA, use a macro with the following statement structure:
If IsEmpty(Cell) Then StatementsIfCellIsEmpty Else StatementsIfCellIsNotEmpty End If
Process Followed by VBA Code to Check if Cell is Empty
VBA Statement Explanation
Line #1: If IsEmpty(Cell) Then
- Item: If… Then.
- VBA Construct: Opening statement of If… Then… Else statement.
- Description: The If… Then… Else statement conditionally executes a group of statements depending on the value of an expression. For these purposes:
- The If… Then… Else statement tests the specified condition (IsEmpty(Cell)).
- If the condition is met and returns True: StatementsIfCellIsEmpty are executed.
- If the condition isn’t met and returns False: StatementsIfCellIsNotEmpty are executed.
- Item: IsEmpty(…).
- VBA Construct: IsEmpty function.
- Description: Generally, the IsEmpty function indicates whether a variable has been initialized. Nonetheless, you can also use IsEmpty to check if a cell is empty.
The IsEmpty function:
- Takes one parameter (expression) of the Variant data type. Within this macro structure, the parameter is a Range object (Cell).
- Returns True if the variable is uninitialized or explicitly set to Empty. Otherwise, IsEmpty returns False.
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties. If you explicitly declare an object variable to represent Cell, use the Range object data type.
- Item: IsEmpty(Cell).
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is an expression that evaluates to True or False. The IsEmpty function (IsEmpty(Cell)) returns True or False, as follows:
- True: Cell is empty.
- False: Cell is not empty.
Line #2: StatementsIfCellIsEmpty
- Item: StatementsIfCellIsEmpty.
- VBA Construct: Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(Cell)) returns True. Within this macro structure, IsEmpty(Cell) returns True if Cell is empty.
Line #3: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statements below the Else clause (StatementsIfCellIsNotEmpty) are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(Cell)) returns False. Within this macro structure, IsEmpty(Cell) returns False if Cell is not empty.
Line #4: StatementsIfCellIsNotEmpty
- Item: StatementsIfCellIsNotEmpty.
- VBA Construct: Else Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(Cell)) returns False. Within this macro structure, IsEmpty(Cell) returns False if Cell is not empty.
Line #5: End If
- Item: End If.
- VBA Construct: Closing statement of If… Then… Else statement.
- Description: The End If clause marks the end of the If… Then… Else block.
Macro Example to Check if Cell is Empty
The following macro example checks if cell A5 of the worksheet named “Check if Cell is Empty” (myCell) is empty and displays a message box confirming whether the cell is empty or not empty.
Sub checkIfCellIsEmpty() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-cell-empty/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'identify cell you work with Set myCell = ThisWorkbook.Worksheets("Check if Cell is Empty").Range("A5") 'check if cell is empty. Depending on result, display message box indicating whether cell is empty (True) or not empty (False) If IsEmpty(myCell) Then MsgBox myCell.Address & " is empty" Else MsgBox myCell.Address & " is not empty" End If End Sub
Effects of Executing Macro Example to Check if Cell is Empty
The following GIF illustrates the results of executing the macro example. Cell A5 (This cell isn’t empty) is not empty and the message box displayed confirms that this is the case.
#2: Check if Active Cell is Empty
VBA Code to Check if Active Cell is Empty
To check if the active cell is empty with VBA, use a macro with the following statement structure:
If IsEmpty(ActiveCell) Then StatementsIfActiveCellIsEmpty Else StatementsIfActiveCellIsNotEmpty End If
Process Followed by VBA Code to Check if Active Cell is Empty
VBA Statement Explanation
Line #1: If IsEmpty(ActiveCell) Then
- Item: If… Then.
- VBA Construct: Opening statement of If… Then… Else statement.
- Description: The If… Then… Else statement conditionally executes a group of statements depending on the value of an expression. For these purposes:
- The If… Then… Else statement tests the specified condition (IsEmpty(ActiveCell)).
- If the condition is met and returns True: StatementsIfActiveCellIsEmpty are executed.
- If the condition isn’t met and returns False: StatementsIfActiveCellIsNotEmpty are executed.
- Item: IsEmpty(…).
- VBA Construct: IsEmpty function.
- Description: Generally, the IsEmpty function indicates whether a variable has been initialized. Nonetheless, you can also use IsEmpty to check if a cell is empty.
The IsEmpty function:
- Takes one parameter (expression) of the Variant data type. Within this macro structure, the parameter is a Range object (ActiveCell).
- Returns True if the variable is uninitialized or explicitly set to Empty. Otherwise, IsEmpty returns False.
- Item: ActiveCell.
- VBA Construct: Application.ActiveCell property.
- Description: The Application.ActiveCell property returns a Range object representing the active cell.
- Item: IsEmpty(ActiveCell).
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is an expression that evaluates to True or False. The IsEmpty function (IsEmpty(ActiveCell)) returns True or False, as follows:
- True: Active cell is empty.
- False: Active cell is not empty.
Line #2: StatementsIfActiveCellIsEmpty
- Item: StatementsIfActiveCellIsEmpty.
- VBA Construct: Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(ActiveCell)) returns True. Within this macro structure, IsEmpty(ActiveCell) returns True if the active cell is empty.
Line #3: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statements below the Else clause (StatementsIfActiveCellIsNotEmpty) are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(ActiveCell)) returns False. Within this macro structure, IsEmpty(ActiveCell) returns False if the active cell is not empty.
Line #4: StatementsIfActiveCellIsNotEmpty
- Item: StatementsIfActiveCellIsNotEmpty.
- VBA Construct: Else Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (IsEmpty(ActiveCell)) returns False. Within this macro structure, IsEmpty(ActiveCell) returns False if the active cell is not empty.
Line #5: End If
- Item: End If.
- VBA Construct: Closing statement of If… Then… Else statement.
- Description: The End If clause marks the end of the If… Then… Else block.
Macro Example to Check if Active Cell is Empty
The following macro example checks if the active cell is empty and displays a message box confirming whether the active cell is empty or not empty.
Sub checkIfActiveCellIsEmpty() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-cell-empty/ 'check if active cell is empty. Depending on result, display message box indicating whether active cell is empty (True) or not empty (False) If IsEmpty(ActiveCell) Then MsgBox "The active cell is empty" Else MsgBox "The active cell is not empty" End If End Sub
Effects of Executing Macro Example to Check if Active Cell is Empty
The following GIF illustrates the results of executing the macro example. The active cell (A6) is empty and the message box displayed confirms that this is the case.
#3: Check if Range is Empty
VBA Code to Check if Range is Empty
To check if a range is empty with VBA, use a macro with the following statement structure:
If WorksheetFunction.CountA(CellRange) = 0 Then StatementsIfRangeIsEmpty Else StatementsIfRangeIsNotEmpty End If
Process Followed by VBA Code to Check if Range is Empty
VBA Statement Explanation
Line #1: If WorksheetFunction.CountA(CellRange) = 0 Then
- Item: If… Then.
- VBA Construct: Opening statement of If… Then… Else statement.
- Description: The If… Then… Else statement conditionally executes a group of statements depending on the value of an expression. For these purposes:
- The If… Then… Else statement tests the specified condition (WorksheetFunction.CountA(CellRange) = 0).
- If the condition is met and returns True: StatementsIfRangeIsEmpty are executed.
- If the condition isn’t met and returns False: StatementsIfRangeIsNotEmpty are executed.
- Item: WorksheetFunction.CountA(…).
- VBA Construct: WorksheetFunction.CountA method.
- Description: The WorksheetFunction.CountA method counts the number of cells that are not empty within the argument list (CellRange). For these purposes, a cell is deemed to not be empty if, for example, it contains an error value or empty text (“”).
- Item: CellRange.
- VBA Construct: Range object.
- Description: Range object representing the cell range you work with.
You can usually return a Range object with constructs such as the Worksheet.Range property. If you explicitly declare an object variable to represent CellRange, use the Range object data type.
- Item: =.
- VBA Construct: = comparison operator.
- Description: The = comparison operator compares the 2 expressions to determine whether they’re equal:
- The expression to the left of the = comparison operator (WorksheetFunction.CountA(CellRange)).
- The expression to the right of the = comparison operator (0).
- Item: WorksheetFunction.CountA(CellRange) = 0.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False. The = comparison operator returns True or False as follows:
- True: If WorksheetFunction.CountA(CellRange) returns 0. This occurs when CellRange is empty.
- False: If WorksheetFunction.CountA(CellRange) returns a value other than 0. This occurs when CellRange isn’t empty.
Line #2: StatementsIfRangeIsEmpty
- Item: StatementsIfRangeIsEmpty.
- VBA Construct: Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) = 0) returns True. Within this macro structure, (WorksheetFunction.CountA(CellRange) = 0) returns True if CellRange is empty.
Line #3: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statements below the Else clause (StatementsIfRangeIsNotEmpty) are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) = 0) returns False. Within this macro structure, (WorksheetFunction.CountA(CellRange) = 0) returns False if CellRange is not empty.
Line #4: StatementsIfRangeIsNotEmpty
- Item: StatementsIfRangeIsNotEmpty.
- VBA Construct: Else Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) = 0) returns False. Within this macro structure, (WorksheetFunction.CountA(CellRange) = 0) returns False if CellRange is not empty.
Line #5: End If
- Item: End If.
- VBA Construct: Closing statement of If… Then… Else statement.
- Description: The End If clause marks the end of the If… Then… Else block.
Macro Example to Check if Range is Empty
The following macro example checks if the range composed of cells A7 through A11 of the worksheet named “Check if Cell is Empty” (myCellRange) is empty and displays a message box confirming whether the range is empty or not empty.
Sub checkIfRangeIsEmpty() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-cell-empty/ 'declare object variable to hold reference to cell range you work with Dim myCellRange As Range 'identify cell range you work with Set myCellRange = ThisWorkbook.Worksheets("Check if Cell is Empty").Range("A7:A11") 'check if number of non-empty cells in range is 0. Depending on result, display message box indicating whether cell range is empty (True) or not empty (False) If WorksheetFunction.CountA(myCellRange) = 0 Then MsgBox myCellRange.Address & " is empty" Else MsgBox myCellRange.Address & " is not empty" End If End Sub
Effects of Executing Macro Example to Check if Range is Empty
The following GIF illustrates the results of executing the macro example. Cells A7 through A11 (with fill) are empty and the message box displayed confirms that this is the case.
#4: Check if Any Cell in Range is Empty
VBA Code to Check if Any Cell in Range is Empty
To check if any cell in a range is empty with VBA, use a macro with the following statement structure:
If WorksheetFunction.CountA(CellRange) < CellRange.Count Then StatementsIfAnyCellInRangeIsEmpty Else StatementsIfNoCellInRangeIsEmpty End If
Process Followed by VBA Code to Check if Any Cell in Range is Empty
VBA Statement Explanation
Line #1: If WorksheetFunction.CountA(CellRange) < CellRange.Count Then
- Item: If… Then.
- VBA Construct: Opening statement of If… Then… Else statement.
- Description: The If… Then… Else statement conditionally executes a group of statements depending on the value of an expression. For these purposes:
- The If… Then… Else statement tests the specified condition (WorksheetFunction.CountA(CellRange) < CellRange.Count).
- If the condition is met and returns True: StatementsIfAnyCellInRangeIsEmpty are executed.
- If the condition isn’t met and returns False: StatementsIfNoCellInRangeIsEmpty are executed.
- Item: WorksheetFunction.CountA(…).
- VBA Construct: WorksheetFunction.CountA method.
- Description: The WorksheetFunction.CountA method counts the number of cells that are not empty within the argument list (CellRange). For these purposes, a cell is deemed to not be empty if, for example, it contains an error value or empty text (“”).
- Item: CellRange.
- VBA Construct: Range object.
- Description: Range object representing the cell range you work with.
You can usually return a Range object with constructs such as the Worksheet.Range property. If you explicitly declare an object variable to represent CellRange, use the Range object data type.
- Item: <.
- VBA Construct: < comparison operator.
- Description: The < comparison operator compares 2 expressions to determine whether (i) the expression to its left (WorksheetFunction.CountA(CellRange)), (ii) is less than (iii) the expression to its right (CellRange.Count).
- Item: CellRange.Count.
- VBA Construct: Range.Count property.
- Description: The Range.Count property returns the number of objects in the collection (CellRange). Within this macro structure, the Count property returns the number of individual cells within CellRange.
- Item: WorksheetFunction.CountA(CellRange) < CellRange.Count.
- VBA Construct: Condition of If… Then… Else statement.
- Description: The condition is an expression that evaluates to True or False. The < comparison operator returns True or False as follows:
- True: If WorksheetFunction.CountA(CellRange) returns a value smaller than the value returned by CellRange.Count. Within this macro structure, this occurs when (i) the number of non-empty cells in CellRange (returned by WorksheetFunction.CountA(CellRange)) (ii) is less than (iii) the number of cells in CellRange (returned by CellRange.Count). This occurs when CellRange contains at least 1 empty cell.
- False: If WorksheetFunction.CountA(CellRange) returns a value equal to the value returned by CellRange.Count. Within this macro structure, this occurs when (i) the number of non-empty cells in CellRange (returned by WorksheetFunction.CountA(CellRange)) (ii) is equal to (iii) the number of cells in CellRange (returned by CellRange.Count). This occurs when CellRange contains no empty cells.
Line #2: StatementsIfAnyCellInRangeIsEmpty
- Item: StatementsIfAnyCellInRangeIsEmpty.
- VBA Construct: Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns True. Within this macro structure, (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns True if CellRange contains at least 1 empty cell.
Line #3: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statements below the Else clause (StatementsIfNoCellInRangeIsEmpty) are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns False. Within this macro structure, (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns False if CellRange doesn’t contain any empty cells.
Line #4: StatementsIfNoCellInRangeIsEmpty
- Item: StatementsIfNoCellInRangeIsEmpty.
- VBA Construct: Else Statements within If… Then… Else statement.
- Description: One or more VBA statements that are executed if the condition tested in the opening statement of the If… Then… Else statement (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns False. Within this macro structure, (WorksheetFunction.CountA(CellRange) < CellRange.Count) returns False if CellRange doesn’t contain any empty cells.
Line #5: End If
- Item: End If.
- VBA Construct: Closing statement of If… Then… Else statement.
- Description: The End If clause marks the end of the If… Then… Else block.
Macro Example to Check if Any Cell in Range is Empty
The following macro example checks if the range composed of cells A13 through A17 of the worksheet named “Check if Cell is Empty” (myCellRange) contains any empty cells and displays a message box confirming whether the range contains or not any empty cells.
Sub checkIfAnyCellInRangeIsEmpty() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-cell-empty/ 'declare object variable to hold reference to cell range you work with Dim myCellRange As Range 'identify cell range you work with Set myCellRange = ThisWorkbook.Worksheets("Check if Cell is Empty").Range("A13:A17") 'check if number of non-empty cells in range is less than total number of cells in range. Depending on result, display message box indicating whether cell range contains any empty cell (True) or not (False) If WorksheetFunction.CountA(myCellRange) < myCellRange.Count Then MsgBox myCellRange.Address & " contains at least 1 empty cell" Else MsgBox myCellRange.Address & " doesn't contain empty cells" End If End Sub
Effects of Executing Macro Example to Check if Any Cell in Range is Empty
The following GIF illustrates the results of executing the macro example. Cell A15 is empty. The message box displayed confirms that the cell range containing cells A13 to A17 (with fill) contains at least one empty cell (A15).
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage within the Microsoft Developer Network:
- Identify the cell or cell range you work with:
- Workbook object.
- Application.ThisWorkbook property.
- Worksheet object.
- Workbook.Worksheets property.
- Range object.
- Worksheet.Range property.
- Worksheet.Cells property.
- Range.Item property.
- Range.Offset property.
- Application.ActiveCell property.
- Test if a cell or cell range is empty:
- If… Then… Else statement.
- IsEmpty function.
- WorksheetFunction.CountA method.
- Range.Count property.
- Comparison operators.
- Display a message box including, among others, the address of a cell or cell range:
- MsgBox function.
- Range.Address property.
- & operator.
- Work with variables and data types:
- Dim statement.
- Set statement.
- = operator.
- Data types:
- Boolean data type.
- String data type.
- Variant data type.
Return to VBA Code Examples
In this article, you will learn how to use the IsEmpty function in VBA to check if a cell is empty. If you want to do the same in Excel, a similar function is the IsBlank function. In this step-by-step tutorial, for all levels of Excel and VBA users, you will see how to use both functions.
Using the IsEmpty function in VBA
As we already mentioned in the introduction, the IsEmpty is the simple function in VBA which checks if a cell is empty. If the selected does not contain any value, the function will return Boolean TRUE. On the other side, if the cell contains a value, the function returns FALSE. Here is the code:
If IsEmpty(Sheet1.Range("A1").Value) = True Then
Sheet1.Range("B1").Value = "The cell A1 is empty"
Else
Sheet1.Range("B1").Value = "The value in A1 is " & Sheet1.Range("A1").Value
End If
In the example, we want to check if the cell A1 in the Sheet1 contains any value. Therefore, if the cell is empty, we will return “The cell A1 is empty” in the cell B1. If the cell contains a value, we will return the value of the cell A1 in the cell B1. Let’s run the code first with empty A1 and then with A1 containing some value:
Image 1. Using the IsEmpty in VBA with the empty cell
Image 2. Using the IsEmpty in VBA with populated cell
Using the IsBlank function in Excel
The IsBlank function also checks if the value of the cell is blank, but this function does not exist in VBA. We’ll see on similar examples how to check if the cell is blank in Excel, using this formula:
=ISBLANK(A1)
Image 3. Using the IsBlank in Excel with blank A1 cell
Image 4. Using the IsBlank in Excel with populated A1 cell
As you can see, we check if the cell A1 is blank and return the result of the function in the cell B1. In Image 3, the result of the function is Boolean TRUE. On the other side, in Image 4, the result of the function is FALSE, as the cell A1 is “11” and is not blank.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
VBA IsEmpty
IsEmpty is a function which is used to check whether the cell being referred to is empty or not. It is very similar to the ISBLANK function in excel. The IsEmpty function in Excel VBA is also called an information function in excel as it gives the information on whether the given cell is blank or not.
IsEmpty function is an inbuilt function in Excel VBA. As explained in the above definition it is used to determine whether the given cell is blank or not. If the given cell is empty we can display a message to the user that the cell is empty and if it is not empty we can display the message that the cell is not empty.
Syntax of IsEmpty in Excel VBA
The syntax for Isempty function is as follows:
We can use this function to check whether a single cell is empty or the whole range of data is empty or not. There are two values returned by this function. One is true while another one is false. If the given cell is blank the function returns the value as true and if the given cell is not blank it gives value as false.
How to Use VBA IsEmpty Function in Excel?
We will learn how to use a VBA IsEmpty function with few examples in excel.
You can download this VBA IsEmpty Excel Template here – VBA IsEmpty Excel Template
VBA IsEmpty – Example #1
First, let us see the value returned by this function how it works.
Follow the below steps to use VBA IsEmpty function in Excel:
Step 1: Go to the developer’s tab and click on visual basic.
Step 2: Write the following code in the project.
Code:
Sub Check1() Dim MyCheck As String MyCheck = IsEmpty(Range("A1").Value) MsgBox MyCheck End Sub
First, let us understand the code written above step by step:
- Check is the name of the subfunction defined.
- Mycheck is the variable we have defined it as a string because the Isempty function returns a logical value.
- Mycheck stores the value of Isempty returned when it checks the cell A1.
- The value stored in Mycheck Variable is displayed by MsgBox function.
Step 3: Run the code by clicking the run button.
We can see that value returned by the function is true as cell A1 is empty.
VBA IsEmpty – Example #2
Now let us use Isempty function with if function to check for a certain cell in a worksheet whether it is blank or not.
Follow the below steps to use VBA IsEmpty function in Excel:
Step 1: In the developer’s tab click on Visual Basic under the code’s section.
Step 2: Write the following code in the code window,
Code:
Sub Sample1() If IsEmpty(Range("A1")) = False Then MsgBox "Cell A1 is not empty" Else MsgBox "Cell A1 is empty" End If End Sub
Let us again understand the code written above once again.
- First, we have defined our subfunction as Sample1.
- We nest Isempty function with If function to check whether cell A1 is empty or not.
- If cell A1 is empty we use msgbox function to display the message that the given cell is empty.
- If the cell A1 is not empty we use msgbox function to display the message that the given cell is not empty.
Step 3: Run the above code by clicking on the run button.
We see the result displayed as cell A1 is empty.
Step 4: Now put a random value in cell A, for example, I have put a value A in cell A1.
Step 5: Now run the code again and we get the following result.
VBA IsEmpty – Example #3
Now let’s use this function to find out whether the given range of cells is blank or not. Earlier we used this function in a single cell. In this example, our data range will be from B1:D7.
Follow the below steps to use VBA IsEmpty function in Excel:
Step 1: In the developer’s tab click on Visual Basic under the code’s section.
Step 2: Write the following code in the code window,
Code:
Sub Sample2() Dim cell As Range Dim bIsEmpty As Boolean bIsEmpty = False For Each cell In Range("B1:D7") If IsEmpty(cell) = True Then bIsEmpty = True Exit For End If Next cell If bIsEmpty = True Then MsgBox "empty cells" Else MsgBox "cells have values!" End If End Sub
Let us understand the above-written code step by step.
- After defining the subfunction as Sample 2 we have defined a variable named cell as Range and B is empty as Boolean as Boolean stores logical values.
- We have predefined that Bisempty will be false if the cell range given is not empty.
- But if the given cell range is empty the Value stored in Bisempty will be true.
- If the value stored in Bisempty variable is true we display a message as Empty cells or if the value stored in the variable is false we display the message as Cells have values.
Step 3: Run the above code by clicking on the run button.
We see the following result displayed as cell A1 is empty.
Things to Remember
There are few things which we need to remember about Isempty Function in Excel VBA:
- Isempty is similar to Isblank function in Excel.
- IsEmpty is an information function.
- IsEmpty function returns a logical value i.e. true or false.
- IsEmpty function can be used of a single cell or for a range of cells.
Recommended Articles
This has been a guide to VBA IsEmpty. Here we discussed how to use Excel VBA IsEmpty Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Copy Paste
- VBA XML
- VBA Subscript out of Range
- VBA IsError
В этом учебном материале вы узнаете, как использовать Excel функцию ISEMPTY с синтаксисом и примерами.
Описание
Функцию ISEMPTY Microsoft Excel можно использовать для проверки пустых ячеек или неинициализированных переменных.
Функция ISEMPTY — это встроенная в Excel функция, которая относится к категории информационных функций. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.
Синтаксис
Синтаксис функции ISEMPTY в Microsoft Excel:
IsEmpty( value )
Аргументы или параметры
- value
- Значение, которое вы хотите проверить.
Еслиvalue
— пустая ячейка или неинициализированная переменная, эта функция вернет True. В противном случае функция вернет False.
Возвращаемое значение
Функция ISEMPTY возвращает True, если value
является пустой ячейкой или неинициализированной переменной.
Функция ISEMPTY возвращает False, если value
является ячейкой или переменной, содержащей значение (т.е. не пусто).
Примечание
- См. также функцию ЕПУСТО (функция рабочего листа).
Применение
- Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Тип функции
- Функция VBA
Пример (как функция VBA)
Функцию ISEMPTY можно использовать только в коде VBA в Microsoft Excel. Мы можем использовать функцию ISEMPTY для проверки ячейки рабочего листа или переменной.
Давайте рассмотрим оба этих случая.
С ячейкой рабочего листа
Если вы хотите проверить, пуста ли ячейка рабочего листа в VBA, вы не можете использовать функцию рабочего листа ЕПУСТО. В VBA необходимо использовать функцию ISEMPTY. Вот пример того, как с помощью функции ISEMPTY проверить, пуста ли ячейка листа:
Sub TestCellA1() ‘Проверяет, является ли значение ячейки A1 пусто If IsEmpty(Range(«A1»).Value) = True Then MsgBox «Ячейка A1 пуста» End If End Sub |
В этом примере мы проверим, пуста ли ячейка A1.
Если ячейка A1 пуста, отобразится сообщение «Ячейка A1 пуста».
С переменной
Функцию ISEMPTY также можно использовать для проверки, инициализирована ли переменная.
Если переменная не была инициализирована, функция ISEMPTY вернет true. В противном случае функция вернет false.
Переменная не инициализирована
Давайте сначала рассмотрим пример, когда переменная не была инициализирована:
Sub TestVariable() Dim LResult ‘Проверить, инициализирована ли переменная If IsEmpty(LResult) = True Then MsgBox «Переменная не инициализирована.» End If End Sub |
В этом примере переменная с именем LResult была объявлена, но не была инициализирована значением. В результате функция ISEMPTY вернет true и отобразит сообщение «Переменная не инициализирована.»
Переменная инициализирована
Теперь мы изменим приведенный выше пример и инициализируем переменную LResult перед вызовом функции ISEMPTY.
Sub TestVariable() Dim LResult ‘Инициализировать переменную с именем LResult LResult = «Google is simply the best search engine!» ‘Проверить, инициализирована ли переменная If IsEmpty(LResult) = True Then MsgBox «Переменная не инициализирована.» End If End Sub |
Поскольку переменная LResult теперь инициализирована значением «Google is simply the best search engine!», Функция ISEMPTY вернет false, и окно сообщения отображаться не будет.