Проверка переменных и выражений с помощью встроенных функций 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 |
В этом учебном материале вы узнаете, как использовать 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, и окно сообщения отображаться не будет.
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
This Excel tutorial explains how to use the Excel ISEMPTY function with syntax and examples.
Description
The Microsoft Excel ISEMPTY function can be used to check for blank cells or uninitialized variables.
The ISEMPTY function is a built-in function in Excel that is categorized as an Information Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Syntax
The syntax for the ISEMPTY function in Microsoft Excel is:
IsEmpty( value )
Parameters or Arguments
- value
- The value that you want to test. If value is a blank cell or uninitialized variable, this function will return TRUE. Otherwise, the function will return FALSE.
Returns
The ISEMPTY function returns TRUE if the value is a blank cell or uninitialized variable.
The ISEMPTY function returns FALSE if the value is a cell or variable that contains a value (ie: is not empty).
Note
- See also the ISBLANK function (worksheet function).
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The ISEMPTY function can only be used in VBA code in Microsoft Excel. We can use the ISEMPTY function to test a worksheet cell or a variable. Let’s look at both of these cases.
With a Worksheet Cell
If you wish to test whether a worksheet cell is empty in VBA, you can not use the worksheet function called ISBLANK. In VBA, you must use the ISEMPTY function.
Here is an example of how to test whether a worksheet cell is empty using the ISEMPTY function:
Sub TestCellA1() 'Test if the value is cell A1 is blank/empty If IsEmpty(Range("A1").Value) = True Then MsgBox "Cell A1 is empty" End If End Sub
In this example, we will test whether cell A1 is empty. If cell A1 is empty, the message «Cell A1 is empty» will be displayed.
With a Variable
The ISEMPTY function can also be used to test whether a variable has been initialized. If the variable has not been initialized, the ISEMPTY function will return true. Otherwise, the function it will return false.
Variable is Uninitialized
Let’s first look at an example of when a variable has not been initialized:
Sub TestVariable() Dim LResult 'Test if the variable has been initialized If IsEmpty(LResult) = True Then MsgBox "Variable has not been initialized." End If End Sub
In this example, the variable called LResult has been declared, but has not been initialized with a value. As a result, the ISEMPTY function will return true and display the message «Variable has not been initialized.«
Variable is Initialized
Now, we will modify the example above and initialize the LResult variable before calling the ISEMPTY function.
Sub TestVariable() Dim LResult 'Initialize the variable called LResult LResult = "TechOnTheNet.com is a great resource!" 'Test if the variable has been initialized If IsEmpty(LResult) = True Then MsgBox "Variable has not been initialized." End If End Sub
Since the LResult variable has now been initialized to the value «TechOnTheNet.com is a great resource!«, the ISEMPTY function will return false and the message box will not be displayed.
IsEmpty is a worksheet function used to find out whether a given cell reference or a range of cells is empty or not. Since it is a worksheet function, we use the Application to use it in VBA. It is the worksheet method in VBA to use this function. This function comes under the logical lists of functions and returns “True” if the reference is empty.
VBA IsEmpty Function
VBA IsEmpty is a logical function that tests whether the selected is empty or not. Since it is a logical function, it will return the results in Boolean values, i.e., TRUE or FALSE.
If the selected cell is empty, it will return TRUE, or else it will return FALSE.
This article will show you how to use the ISEMPTY function in VBA to check the cells using VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
Table of contents
- VBA IsEmpty Function
- What Does ISEMPTY Function Do in VBA?
- Examples of ISEMPTY Function in VBA
- Example #1
- Example #2 – Combination of VBA ISEMPTY with IF Condition
- Example #3 – Alternative to VBA ISEMPTY Function
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IsEmpty (wallstreetmojo.com)
What Does ISEMPTY Function Do in VBA?
Often empty cells frustrate us from working efficiently on the worksheet. Finding the blank cells is not the hardest, but if empty cells hide them in the middle of the data, it takes a toll to find them.
To find the empty cells in Excel, we have the ” ISBLANK ” function as a worksheet function, but in VBA, it is called “ISEMPTY.”
It works similarly to the worksheet function “ISBLANK”. Now, look at the below formula of the “ISEMPTY” function.
As we can see in the above image, it returns the result as Boolean, i.e., TRUE or FALSE.
Examples of ISEMPTY Function in VBA
The following are examples of IsEmpty in VBA.
You can download this VBA IsEmpty Excel Template here – VBA IsEmpty Excel Template
Example #1
Now, we will see the first practical example of “ISEMPTY.” For this, take a look at the below image of the worksheet.
Now, we will apply Excel VBA ISEMPTY function to test all these.
Step 1: Define the variable as Boolean.
Code:
Sub IsEmpty_Example1() Dim K As Boolean End Sub
Step 2: Assign the value through VBA ISEMPTY function for this variable.
Code:
Sub IsEmpty_Example1() Dim K As Boolean K = IsEmpty( End Sub
Step 3: Expression is nothing but what is the cell we are testing. Now, we are testing the A1 cell.
Code:
Sub IsEmpty_Example1() Dim K As Boolean K = IsEmpty(Range("A1").Value) End Sub
Step 4: Show the value of this variable in the VBA Msgbox.
Code:
Sub IsEmpty_Example1() Dim K As Boolean K = IsEmpty(Range("A1").Value) MsgBox K End Sub
Run this code to check the result.
Since there is a value in cell A1, we got the result as FALSE.
Now, we will change the cell reference from A1 to A5.
Code:
Sub IsEmpty_Example1() Dim K As Boolean K = IsEmpty(Range("A5").Value) MsgBox K End Sub
Run this code to see the result.
We got the result as TRUE. The referenced cell A5 is an empty cell, so we got the result as “TRUE.”
Now, we will test cell A8.
Code:
Sub IsEmpty_Example1() Dim K As Boolean K = IsEmpty(Range("A8").Value) MsgBox K End Sub
Run this code to see the result.
We got the result as FALSE even though there is no value in cell A8.
Now, is it an error result from the ISEMPTY formula?
No… Absolutely No!
When examining cell A8, there was a space character inside the cell that is not easy to see with bare eyes.
So, the conclusion is even space is considered a character in Excel and VBA language.
Example #2 – Combination of VBA ISEMPTY with IF Condition
The real usage of the function “ISEMPTY” is admirable when we use it with other logical functions.
Especially when we use it with IF conditions, we can derive many useful results from it.
For this demonstration, take a look at the below example.
In the “Status” column, if the “PF Status” column is empty, we need the value “No Update.” If there is any value, we need the values as “Collected Updates.”
Remember here that we do not need the default result of TRUE or FALSE. We need our results here. We need to use Excel VBA ISEMPTY with IF conditions to have our results.
Step 1: Open IF condition.
Code:
Sub IsEmpty_Example2() If End Sub
Step 2: Inside the IF condition, open the ISEMPTY function.
Code:
Sub IsEmpty_Example2() If IsEmpty( End Sub
Step 3: The first logical test is cell B2 value is empty or not.
Code:
Sub IsEmpty_Example2() If IsEmpty(Range("B2").Value) Then End Sub
Step 4: If the logical test in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more VBA is TRUE, i.e., if the cell is empty, we need the resultas “No Update” in cell C2.
Code:
Sub IsEmpty_Example2() If IsEmpty(Range("B2").Value) Then Range("C2").Value = "No Update" End Sub
Step 5: If the logical test is FALSE, we need the result in cell C2 as “Collected Updates.”
Code:
Sub IsEmpty_Example2() If IsEmpty(Range("B2").Value) Then Range("C2").Value = "No Update" Else Range("C2").Value = "Collects Updates" End If End Sub
We have completed it now.
Run the code to get the result.
We got the “Collected Updates” result because we have the non-empty cell in B2.
Now, similarly, apply the code for other cells to test.
Code:
Sub IsEmpty_Example2() If IsEmpty(Range("B2").Value) Then Range("C2").Value = "No Update" Else Range("C2").Value = "Collects Updates" End If If IsEmpty(Range("B3").Value) Then Range("C3").Value = "No Update" Else Range("C3").Value = "Collected Updates" End If If IsEmpty(Range("B4").Value) Then Range("C4").Value = "No Update" Else Range("C4").Value = "Collected Updates" End If End Sub
Run this code to have the results.
In cell C3, we got the result as “No Update” because there is no value in cell B3, i.e., an empty cell. Since the logical formula returned TRUE, we got the individual result.
Example #3 – Alternative to VBA ISEMPTY Function
We have an alternative to the ISEMPTY function; without applying the Excel VBA ISEMPTY function, we can test the cell.
For an example, look at the below code.
Code:
Sub IsEmpty_Example3() If Range("B2").Value = "" Then Range("C2").Value = "No Update" Else Range("C2").Value = "Collected Updates" End If End Sub
The line of code Range(“B2″).Value = ” ” means whether the cell B2 cell is equal to empty or not.
Double Quotes (“”) represent an empty cell or not if the empty result is TRUE or else FALSE.
Recommended Articles
This article has been a guide to VBA ISEMPTY function. Here, we learned how to use the VBA ISEMPTY function in Excel, the Combination of IsEmpty with the IF condition, some practical examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –
- Boolean in VBA
- False Function in Excel
- OFFSET in VBA
- Date Function in VBA
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!
What is VBA IsEmpty function?
- The IsEmpty function is used to check if a cell in an Excel sheet is empty.
- This function is also used to check if a variable is initialized.
- It returns True if the variable is uninitialized.
- It also returns True if a variable is explicitly kept empty.
- If a variable is assigned a value, IsEmpty returns False.
An example of using IsEmpty with a sheet cell
Let us first start IsEmpty function with an Excel sheet.
We will use a range and then check if the B3 cell is empty or not.
The status is displayed in the message box.
VBA Code:
Sub IsEmpty_ex() If IsEmpty(Range(«C3»).Value) = True Then MsgBox «Cell C3 is empty» Else MsgBox Range(«C3»).Value End If End Sub |
Result:
You can see, the result is True if the cell is empty.
Iterating through a range and filling empty cells with background color
For this example, we will create a range of B2 to D5 cells and check if any of the cells are empty.
For the empty cells found, we will fill the interior color of the cell by Font.InteriorColor property:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Sub IsEmpty_ex() Dim ChkRange As Range Dim cell ‘Range to be checked for empty cells Set ChkRange = Range(«B2:D5») For Each cell In ChkRange ‘Using IsEmpty in if statement and assign the Interior color if cell is empty If IsEmpty(cell) = True Then cell.Interior.ColorIndex = 3 End If Next cell End Sub |
Result:
You may compare the empty cells filled in this graphic with the first example’s graphic.
Write a value to empty cells example
You may also write some value to the empty cells rather than filling it with color.
In the example below, we will write “Absent” to all cells that are empty in our range:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Sub IsEmpty_ex() Dim ChkRange As Range Dim cell ‘Range to be checked for empty cells Set ChkRange = Range(«B2:D5») For Each cell In ChkRange ‘Write Absent to all empty cells If IsEmpty(cell) = True Then cell.Value = «Absent» End If Next cell End Sub |
Output:
Using IsEmpty with a variable example
Let us use the IsEmpty function with variables in VBA now.
We are using two variables, out of which one is assigned a value (var2 and one is not initialized (var1).
In the IsEmpty function, we will pass these variables and see the returned results:
Sub IsEmpty_ex() Dim var1 Dim var2 MsgBox «IsEmpty returned for var1 = « & IsEmpty(var1) var2 = «Not empty» MsgBox «IsEmpty returned for var2 = « & IsEmpty(var2) End Sub |
Output:
And
I have used the following VBA code:
Do While .Cell(i,1) <> Empty
' doing things
i = i+1
Loop
to iterate through columns (with Double/Integer values) in Excel. Then I found a case where the test evaluates to False whenever the value of the cell is 0. I have no idea what the difference is between this case and the working ones.
If I change the test to:
Do While Not IsEmpty(.Cell(i,1))
..
Loop
it works fine. So my question is: What is the difference between how IsEmpty() and =Empty is evaluated? In what cases will =Empty evaluate to True for cells with value 0?
asked Dec 15, 2011 at 15:17
2
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
answered Dec 15, 2011 at 16:15
Justin SelfJustin Self
6,0773 gold badges31 silver badges48 bronze badges
3
From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.
To check if a cell is empty, you can use cell(x,y) = ""
.
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks)
or xlCellTypeConstants
or xlCellTypeFormulas
answered Dec 15, 2011 at 16:22
iDevlopiDevlop
24.6k11 gold badges89 silver badges147 bronze badges
1
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so:
IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
answered Dec 15, 2011 at 15:19
4