Проверка переменных и выражений с помощью встроенных функций 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 |
idexter08
Пользователь
Сообщений: 27
Регистрация: 20.01.2015
TSN, спасибо) Скажите, а если я хочу очистить не только активную ячейку, а еще несколько конкретных ячеек этой строки, то как мне реализовать и их очистку при нажатии Yes?
Я прошу прощения за наглость, просто пришел к выводу повесить манипуляции все на кнопки(макросы с шорт катами назначенными мной), и если раньше после очистки этой ячейки остальные в этой строке (-ах, если удаляю сразу несколько проектов (соответственно строк)) удалялись сами, благодаря прописанному коду в исходном тексте листа, то сейчас я решил завязать все в одно макросе и прикрепить его к шорт кату и кнопке.
Попытки присобачить сюда код с исходного текста, который позволял очищать остальные ячейки в строке по логике «если пусто, то…», не увенчались успехом.
То есть с учетом всех условий выше: если выбранный диапазон (то есть даже не одна ячейка может быть, то бишь selection) принадлежит к столбцу B (и тут можно даже опустить условие, если я выберу пустую ячейку, пес с ней, не страшно), то: 1) очистить выбранный диапазон 2) очистить соответствующие этому дипазону ячейки в столбцах A, C, E, G, I и K
То есть, я выбрал например диапазон B13:B25, макрос посмотрел, что главное условие выполнено и ячейки выделены только в столбце B (если нет, то пусть выводит сообщение «Выберете ячейку(диапазон) в колонке B и повторите действие еще раз»), он меня спрашивает «Данные этого проекта будут полностью удалены. Продолжить?» и если я жму да, то очищаются не только B13:B25, но и те же диапазоны в столбцах A, C, E, G, I и K
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.
-
#1
Hi All,
I’m working with a this code below that works great!
It first checks on sheet1 cell D3 to first see if there is a value before it provides a date stamp.
Here is the code:
Code:
Sub Macro16()
'
' Macro16 Macro
'
'
Application.Cursor = xlWait 'during processing
If Not IsEmpty(Sheet1.Range("D3").Value) Then
MsgBox ("This was already executed! Please use the SAVE ICON at the TOP LEFT TO SAVE YOUR DOCUMENT!")
Application.Cursor = xlDefault 'on completion / error
Exit Sub
End If
Call UNLockCell
Call AddDateStamp
Call SaveAsXLSM
Application.Cursor = xlDefault 'on completion / error
End Sub
Now my question is, when I change this code to execute it for another sheet, for example sheet10 in the code below it does not work and I can’t figure it out.
Code:
Sub Macro33()
'
' Macro33 Macro
'
'
If IsEmpty(Sheet10.Range("B2").Value) Then
MsgBox ("The IMPORT HAS to be executed FIRST!!")
Exit Sub
End If
Application.Cursor = xlDefault 'on completion / error
End Sub
If I type a date into sheet10 cell B2, I’d expect the MsgBox to popup
The IMPORT HAS to be executed FIRST!!
in using Macro33 above, but it does not (?).
Can someone try and help me out on this?
Thanks,
Pin
EXCEL FORMULA 1. If a cell is not blank using the IF function
EXCEL
Hard coded formula
Cell reference formula
GENERIC FORMULA =IF(cell_ref<>»», value_if_true, value_if_false) ARGUMENTS GENERIC FORMULA =IF(cell_ref<>»», value_if_true, value_if_false) ARGUMENTS EXPLANATION This formula uses the IF function with a test criteria of two double quotation marks («»), without any value inserted between them and ‘does not equal to’ sign (<>) in front of them, to assess if a cell is not empty and return a specific value. The expression <>»» means «not empty». If a cell is not blank the formula will return a value that has been assigned as the true value, alternatively if a cell is blank the formula will return a value assigned as the false value. With this formula you can enter the values, that will be returned if the cell is empty or not, directly into the formula or reference them to specific cells that capture these values. Click on either the Hard Coded or Cell Reference button to view the formula that has the return values directly entered into the formula or referenced to specific cells that capture these values, respectively. In this example the formula tests if a specific cell is not blank. If the cell is not blank the formula will return a value of «Yes» (hard coded example) or value in cell C5 (cell reference example). If the cell is empty the formula will return a value of «No» (hard coded example) or value in cell C6 (cell reference example). If you are using the formula with values entered directly in the formula and want to return a numerical value, instead of a text value, you do not need to apply the double quotation marks around the values that are to be returned e.g. (=IF(C5<>»»,1,0)). |
EXCEL FORMULA 2. If a cell is not blank using the IF, NOT and ISBLANK functions
EXCEL
Hard coded formula
Cell reference formula
GENERIC FORMULA =IF(NOT(ISBLANK(cell_ref)), value_if_true, value_if_false) ARGUMENTS GENERIC FORMULA =IF(NOT(ISBLANK(cell_ref)), value_if_true, value_if_false) ARGUMENTS EXPLANATION This formula uses a combination of the IF, NOT and ISBLANK functions to assess if a cell is not blank and return a specific value. Unlike the first formula, which uses the double quotation marks («») to test if the selected cell is not blank, this formula uses the NOT and ISBLANK functions. If the cell is not blank the ISBLANK function will return FALSE, alternatively it will return TRUE. The NOT function will then return the opposite to what the ISBLANK function has returned. Therefore, if the cell is not blank the combination of the NOT and ISBLANK function will return a TRUE value. The formula will then return a value that has been assigned as the true value, alternatively if the cell is blank the formula will return a value assigned as the false value. With this formula you can enter the values, that will be returned if the cell is empty or not, directly into the formula or reference them to specific cells that capture these values. Click on either the Hard Coded or Cell Reference button to view the formula that has the return values directly entered into the formula or referenced to specific cells that capture these values, respectively. In this example the formula tests if a specific cell is not blank. If the cell is not blank the formula will return a value of «Yes» (hard coded example) or value in cell C5 (cell reference example). If the cell is empty the formula will return a value of «No» (hard coded example) or value in cell C6 (cell reference example). If you are using the formula with values entered directly in the formula and want to return a numerical value, instead of a text value, you do not need to apply the double quotation marks around the values that are to be returned e.g. (=IF(NOT(ISBLANK(C5)),1,0)). |
VBA CODE 1. If a cell is not blank using the If Statement
VBA
Hard coded against single cell
Sub If_a_cell_is_not_blank()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If ws.Range(«C5») <> «» Then
ws.Range(«D5») = «Yes»
Else
ws.Range(«D5») = «No»
End If
End Sub
Cell reference against single cell
Sub If_a_cell_is_not_blank()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If ws.Range(«C9») <> «» Then
ws.Range(«D9») = ws.Range(«C5»)
Else
ws.Range(«D9») = ws.Range(«C6»)
End If
End Sub
Hard coded against range of cells
Sub If_a_cell_is_not_blank()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 5 To 11
If ws.Cells(x, 3) <> «» Then
ws.Cells(x, 4) = «Yes»
Else
ws.Cells(x, 4) = «No»
End If
Next x
End Sub
Cell reference against range of cells
Sub If_a_cell_is_not_blank()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 9 To 15
If ws.Cells(x, 3) <> «» Then
ws.Cells(x, 4) = ws.Range(«C5»)
Else
ws.Cells(x, 4) = ws.Range(«C6»)
End If
Next x
End Sub
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D5») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C5») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D9») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C9») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
KEY PARAMETERS
Output and Test Range: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (5 to 11). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output and Test Range: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (9 to 15). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
VBA CODE 2. If a cell is not blank using Not and IsEmpty
VBA
Hard coded against single cell
Sub If_a_cell_is_not_blank_using_Not_and_IsEmpty()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If Not (IsEmpty(ws.Range(«C5»)))Then
ws.Range(«D5») = «Yes»
Else
ws.Range(«D5») = «No»
End If
End Sub
Cell reference against single cell
Sub If_a_cell_is_not_blank_using_Not_and_IsEmpty()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If Not (IsEmpty(ws.Range(«C9»)))Then
ws.Range(«D9») = ws.Range(«C5»)
Else
ws.Range(«D9») = ws.Range(«C6»)
End If
End Sub
Hard coded against range of cells
Sub If_a_cell_is_not_blank_using_Not_and_IsEmpty()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 5 To 11
If Not (IsEmpty(ws.Cells(x, 3))) Then
ws.Cells(x, 4) = «Yes»
Else
ws.Cells(x, 4) = «No»
End If
Next x
End Sub
Cell reference against range of cells
Sub If_a_cell_is_not_blank_using_Not_and_IsEmpty()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 9 To 15
If Not (IsEmpty(ws.Cells(x, 3))) Then
ws.Cells(x, 4) = ws.Range(«C5»)
Else
ws.Cells(x, 4) = ws.Range(«C6»)
End If
Next x
End Sub
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D5») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C5») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as not blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D9») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C9») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as not blank.
KEY PARAMETERS
Output and Test Range: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (5 to 11). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output and Test Range: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (9 to 15). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
VBA CODE 3. If a cell is not blank using vbNullString
VBA
Hard coded against single cell
Sub If_a_cell_is_not_blank_using_vbNullString()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If ws.Range(«C5») <> vbNullString Then
ws.Range(«D5») = «Yes»
Else
ws.Range(«D5») = «No»
End If
End Sub
Cell reference against single cell
Sub If_a_cell_is_not_blank_using_vbNullString()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
If ws.Range(«C9») <> vbNullString Then
ws.Range(«D9») = ws.Range(«C5»)
Else
ws.Range(«D9») = ws.Range(«C6»)
End If
End Sub
Hard coded against range of cells
Sub If_a_cell_is_not_blank_using_vbNullString()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 5 To 11
If ws.Cells(x, 3) <> vbNullString Then
ws.Cells(x, 4) = «Yes»
Else
ws.Cells(x, 4) = «No»
End If
Next x
End Sub
Cell reference against range of cells
Sub If_a_cell_is_not_blank_using_vbNullString()
Dim ws As Worksheet
Set ws = Worksheets(«Analysis»)
For x = 9 To 15
If ws.Cells(x, 3) <> vbNullString Then
ws.Cells(x, 4) = ws.Range(«C5»)
Else
ws.Cells(x, 4) = ws.Range(«C6»)
End If
Next x
End Sub
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D5») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C5») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output Range: Select the output range by changing the cell reference («D9») in the VBA code.
Cell to Test: Select the cell that you want to check if it’s not blank by changing the cell reference («C9») in the VBA code.
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
KEY PARAMETERS
Output and Test Rows: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (5 to 11). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value of «Yes». If a cell is blank the VBA code will return a value of «No». Both of these values can be changed to whatever value you desire by directly changing them in the VBA code.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
Note 2: If your True or False result is a text value it will need to be captured within quotation marks («»). However, if the result is a numeric value, you can enter it without the use of quotation marks.
KEY PARAMETERS
Output and Test Rows: Select the output rows and the rows that captures the cells that are to be tested by changing the x values (9 to 15). This example assumes that both the output and the associated test cell will be in the same row.
Test Column: Select the column that captures the cells that are to be tested by changing number 3, in ws.Cells(x, 3).
Output Column: Select the output column by changing number 4, in ws.Cells(x, 4).
Worksheet Selection: Select the worksheet which captures the cells that you want to test if they are not blank and return a specific value by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.
True and False Results: In this example if a cell is not blank the VBA code will return a value stored in cell C5. If a cell is blank the VBA code will return a value stored in cell C6. Both of these values can be changed to whatever value you desire by either referencing to a different cell that captures the value that you want to return or change the values in those cells.
NOTES
Note 1: If the cell that is being tested is returning a value of («») this VBA code will identify the cell as blank.
*Note:* This post was originally posted on my blog. I hope posting it here will help reach those whom it will help.
Recently I have been using VBA for a project in Excel and, though I know what I want to express in VBA, I don’t always know the syntax since it isn’t my main programming language. I had to look up the syntax for the if / else conditional clause and how to check whether a string variable is empty. Given that I’m an experienced software engineer and still had to look them up I thought sharing them with you here would be helpful.
Note: Don’t just copy and paste before reading the article. Copying and pasting without understanding is unwise. You do so at your own danger.
If – Then – Else Conditional Statements In VBA
The if – else conditional statement is a staple of any programming language. In each language they have the same meaning. That is if some condition is true then take some action. Otherwise do something else or skip the action. Each language, however, has a slightly different way of saying this; that is each language has a different syntax.
In the case of VBA this is handled as follows (and as described in this guide on Microsoft’s docs website. The documentation is here):
If [condition] Then
' code
ElseIf [condition] Then
' code
Else
' code
End If
Checking String Variables For Emptiness
There are two common checks needed when dealing with data coming from a source outside the control of code you’re writing. These are:
- Did I get data or is it empty?
- Does the data conform to what I expect and can deal with?
In the case of the code I was writing I’ve got a class with member variables some of which are optional. When I am going to use them to pass the data on I need to know if there is data present to decide what to do with them. The last piece of pertinent information is that I am treating all the variables as strings because I will be sending the data over an API.
Can We Use The IsEmpty() function?
My initial search for how to check whether a string is empty led me to the IsEmpty() function. This seems like a really good fit for what I was looking for. As described in the documentation:
Returns a Boolean value indicating whether a variable has been initialized.
Given that I want to check whether a member variable of my class has been initialized to a value this looks like exactly what I want. As I was about to write this, however, I thought it would be a good idea to test this just to make sure that I am giving you correct information. As such, I wrote this small bit of code:
Sub CheckVarForEmpty()
Dim stringVar As String
If IsEmpty(stringVar) = True Then
MsgBox "Variable Is Empty!"
End If
End Sub
After writing this I ran this fully expecting to have a message box pop up saying that the variable is empty. However it did NOT pop up.
VBA Debugger To The Rescue!
However, when I debugged the code to make sure that the message box was really being skipped, I noticed that the variable showed that it had the value “”. Now, to me, this looks like an empty string but I decided to write another conditional testing the value of the string against “”:
Sub CheckVarForEmpty()
Dim stringVar As String
If stringVar = "" Then
MsgBox "Varable Is = to Empty String"
End If
End Sub
Sure enough the message box is shown. Hooray! This means that checking a string against “” successfully determines if a string variable is empty.
Why Didn’t IsEmpty() Work?
However, because I was curious I why IsEmpty() did not return true in my first attempt, I went back to the documentation and read it again. It specifically says that IsEmpty() only returns True if a variable is not initialized or explicitly set to Empty. If you notice in my first example I declare stringVar as a string because I am used to programming in strongly typed languages and it makes sense to me to mark how a variable is to be used. Given that the documentation for IsEmpty() shows examples where the variables were NOT declared with types. This made me wonder if, by declaring a variable with a type, it initializes it to a value (“” in the case of strings). This would make IsEmpty() return False. As such I wrote another test to see if this train of thought is valid:
Sub CheckVarForEmpty()
Dim myVar
If IsEmpty(myVar) = True Then
MsgBox "MyVar is Empty!"
End If
End Sub
Sure enough the message box in this test popped up as the documentation indicated it would. This, for me, confirms that declaring a variable in VBA as a particular type will initialize it in a manner appropriate for that type.
Conclusion — I always have more to learn
This exercise shows that, despite my years of experience, there are always more things to learn. I hope that this helps you in your adventures in VBA. For me, the next things I will teach myself regarding VBA is more about how classes are constructed and destructed. I hope to bring you more knowledge as I gain it for myself.
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