Excel vba finding empty cell

Excel VBA Tutorial about how to check if cell or range is empty with macros

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

Check if Cell is empty > Execute StatementsIfCellIsEmpty or StatementsIfCellIsNotEmpty

VBA Statement Explanation

Line #1: If IsEmpty(Cell) Then

  1. 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.
  2. 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.
  3. 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.

  4. 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

  1. 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

  1. 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

  1. 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

  1. 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.

Macro checks if cell is empty

#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

Check if active cell is empty > Execute StatementsIfActiveCellIsEmpty or StatementsIfActiveCellIsNotEmpty

VBA Statement Explanation

Line #1: If IsEmpty(ActiveCell) Then

  1. 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.
  2. 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.
  3. Item: ActiveCell.
    • VBA Construct: Application.ActiveCell property.
    • Description: The Application.ActiveCell property returns a Range object representing the active cell.
  4. 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

  1. 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

  1. 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

  1. 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

  1. 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.

Macro checks if active cell is empty

#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

Check if number of non-empty cells in range is 0 > Execute StatementsIfRangeIsEmpty or StatementsIfRangeIsNotEmpty

VBA Statement Explanation

Line #1: If WorksheetFunction.CountA(CellRange) = 0 Then

  1. 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.
  2. 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 (“”).
  3. 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.

  4. 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).
  5. 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

  1. 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

  1. 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

  1. 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

  1. 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.

Macro checks if range is empty

#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

Check if number of non-empty cells in range is less than total number of cells in range > Execute StatementsIfAnyCellInRangeIsEmpty or StatementsIfNoCellInRangeIsEmpty

VBA Statement Explanation

Line #1: If WorksheetFunction.CountA(CellRange) < CellRange.Count Then

  1. 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.
  2. 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 (“”).
  3. 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.

  4. 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).
  5. 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.
  6. 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

  1. 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

  1. 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

  1. 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

  1. 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).

Macro checks if any cell in range is empty

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage within the Microsoft Developer Network:

  1. 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.
  2. Test if a cell or cell range is empty:
    • If… Then… Else statement.
    • IsEmpty function.
    • WorksheetFunction.CountA method.
    • Range.Count property.
    • Comparison operators.
  3. Display a message box including, among others, the address of a cell or cell range:
    • MsgBox function.
    • Range.Address property.
    • & operator.
  4. Work with variables and data types:
    • Dim statement.
    • Set statement.
    • = operator.
    • Data types:
      • Boolean data type.
      • String data type.
      • Variant data type.

 

Подскажите как при помощи VBA определить наличие пустой ячейки (не заполненной = «» ;)  в диапазоне (например А1:С300) или ячейки с значением = 0 ?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Нашли, дальше что? Перебрать диапазон/массив и при нахождении пустой/нулевой выйти из цикла с сообщением.

 

Антон

Пользователь

Сообщений: 617
Регистрация: 01.01.1970

#3

28.01.2014 01:20:21

посредством перебора каждого значения массива и сравнением )

Код
'перебираем строки 
For i=1 to 300 
'перебираем столбцы 
For y=1 to 3 
If cells(i,y).Value="" then 
Msgbox("пустая ячейка") 
Exit for
End if 
If cells(i,y).Value=0 then 
Msgbox("нуль.")  
Exit for 
End if    
Next y   
Next i

Изменено: Антон28.01.2014 01:25:02

 

Да, если такие ячейки имеются вывести сообщение и прекратить дальнейшее выполнение макроса, если таких ячеек нет продолжить выполнение макроса.

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#5

28.01.2014 01:28:51

Код
Sub Test()
Dim Rng As Range, rCell As Range
    Set Rng = Range("A1:C300")
    For Each rCell In Rng
        If IsEmpty(rCell) Or rCell = 0 Then
            MsgBox "Найдено в ячейке " & rCell.Address(0, 0), 64, "Для сведения"
            Exit For
        End If
    Next
End Sub 
 
 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#7

28.01.2014 02:01:36

Без цикла, но и без адресов:

Код
Sub Test2()
Dim Rng As Range
    Set Rng = Range("A1:C300")
    x = Application.WorksheetFunction.CountA(Rng)
    y = Application.WorksheetFunction.CountIf(Rng, 0)
    If Rng.Cells.Count <> x Then MsgBox "Есть пустые."
    If y > 0 Then MsgBox "Есть нули."
End Sub 
 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Я сам — дурнее всякого примера! …

 

Max.il

Пользователь

Сообщений: 64
Регистрация: 05.12.2018

Юрий М, Юрий, добрый вечер. Развивая тему, если нужно проверить несколько ячеек, к примеру А3, Т16 и Т22, если они пустые — залить эту ячейку красным цветом. Если в ней есть что-то , пропустить. Если во всех ячейках есть данные, то просто прекратить выполнение макроса без вывода сообщения.
Спасибо  

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

 

Max.il

Пользователь

Сообщений: 64
Регистрация: 05.12.2018

Юрий М,Нет, т.к. проверка должна осуществляться после макроса.  

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

УФ сработает и после макроса. А макрос написать не смогу: нет у меня файла, где имеются перечисленные Вами ячейки ))
Вы бы уточнили: три ячейки — это только для примера? А по факту? И как макрос должен понять, какие именно ячейки проверять? Где-то есть список этих ячеек?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#13

27.05.2019 23:32:23

Нет ответа…

Код
Dim rCell As Range
    For Each rCell In Range("A3, T16, T22")
        If rCell = "" Then
            rCell.Interior.ColorIndex = 3
        Else
            rCell.Interior.ColorIndex = xlNone
        End If
    Next
 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#14

27.05.2019 23:39:10

Цитата
Max.il написал:
к примеру
Код
Sub qq()
    Dim r As Range
    Set r = [a1:c3]
    On Error Resume Next
    r.SpecialCells(4).Interior.ColorIndex = 3
End Sub
 

Max.il

Пользователь

Сообщений: 64
Регистрация: 05.12.2018

RAN,  Юрий М, Мужчины, спасибо, что помогаете . Искренняя благодарность.  

 

Николай Китаев

Пользователь

Сообщений: 2
Регистрация: 01.01.1970

#16

17.12.2021 13:26:01

Цитата
написал:
Подскажите как при помощи VBA определить наличие пустой ячейки

Такая конструкция не работает: If cells(i,y).Value=»» then….

А так — должно работать:
If IsEmpty(cells(i,y).Value) = True Then ……., где К — переменная содержащая или несодержащая значение, или переменная, содержащая адрес ячейки Cell, которую проверяем.

Изменено: Николай Китаев17.12.2021 14:07:17

 

Jack Famous

Пользователь

Сообщений: 10846
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Николай Китаев, с момента создания темы прошло почти 8 лет, а ТС был последний раз почти 2 года назад — в курсе?  :D

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Ничего страшного. Можно считать, что памятка для себя. Тем более проверка вида cells(i,y).Value=»» не работает.

 

БМВ

Модератор

Сообщений: 21376
Регистрация: 28.12.2016

Excel 2013, 2016

#19

17.12.2021 14:19:40

Цитата
Николай Китаев написал:
Тем более проверка вида cells(i,y).Value=»» не работает.

докажите.

По вопросам из тем форума, личку не читаю.

 

Jack Famous

Пользователь

Сообщений: 10846
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Если вас что-то не устраивает, то не нужно поднимать со дна старую тему, тем более, что спросить автора не получится — создайте свою и там всё подробно опишите и/или спросите

И тут гляньте:

VBA. UDF. Функция для проверки значения на строку нулевой длины «=»»»

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#21

17.12.2021 23:29:31

Цитата
Николай Китаев написал: If IsEmpty(cells(i,y).Value) = True Then ……., где К — переменная

И где К? )

  • Remove From My Forums
  • Question

  • Hello Sir,
    
    Pls, i have to find the 'NoEmpty' cell at 24,35
    and to get the ligne adresse '218'
    
    Many thanks for your help
    
    My best Regards
    Arnold
    
    ==============
    This vba stuff works ~
    
    Function NoEmpty() As String
    Dim Ligne As Long, Cptr As Long
        Application.Volatile
        Do While Cptr < 24 And Ligne < Rows.Count
            Ligne = Ligne + 1
            If Cells(Ligne, 35) = "" Then
                Cptr = Cptr + 1
            End If
        Loop
        If Cptr = 24 Then
            NoEmpty = Cells(Ligne, 35).Address
        Else
            NoEmpty = "Hors limite"
        End If
    End Function
    =====================
    
    cls
    
    $path = "C:MMCtest.file.xlsx"
    $xl = New-Object -com Excel.Application
    $xl.DisplayAlerts = $False
    $wb = $xl.WorkBooks.Open($path)
    $wb.ForceFullCalculation = $True
    
    $t = "text"
    
    $test = $wb.ActiveSheet.Cells.Item(  'VBA stuff ???' ,35).$t # 218
     
    $ligne = [int]$test - 40
    
    $ligne.. $test | $wb.ActiveSheet.Cells.Item($ligne,35).$t)
    
    $xl.WorkBooks.Close()
    
    $xl.quit()
    $xl = $null
    [gc]::collect()
    [gc]::WaitForPendingFinalizers()
    
    

    • Moved by

      Saturday, March 8, 2014 1:46 PM
      Moving to more appropriate forum

Answers

  • Hi Sir,
    Many thanks for your reply!
    I will us your last suggestion. Great!
    
    My best Regards
    Arnold
    NB: Sorry for all
    =======================
    I have modify at the last time this: (it works but .... )
    
    cls
    
    $Xpath = "C:MMC3DCityMain.xlsx"
    $Xxl = New-Object -com Excel.Application
    $Xxl.DisplayAlerts = $False
    $Xwb = $Xxl.WorkBooks.Open($Xpath)
    $Xwb.ForceFullCalculation = $True
    
    $Xt = "text"
    
    $Xstart_row = 170
    $Xrow = $Xstart_row
    $Xcell_row = Do{$Xrow; $Xrow++} until ($Xwb.ActiveSheet.cells.Item($Xrow,35).$Xt -eq "")
    
    $Xhead = "Lnr | Time | Txt ......"
    $Xhead
    
    for ($Xi = 1; $Xi -lt $Xcell_row.Count)
      {
    		$Xstart_row..$Xrow | % 
                     {
    				if ($Xi % 10 -eq 0)
                		{
    		      			$Xhead
    			}
    		[string]$Xi+" "+($Xwb.ActiveSheet.Cells.Item(($_ -1),35).$t); $Xi ++ }
      }
    
    $Xxl.WorkBooks.Close()
    
    $Xxl.quit()
    $Xxl = $null
    [gc]::collect()
    [gc]::WaitForPendingFinalizers()
    
    clear-variable X* -scope global -f
    
    <#
    Lnr | Time | Txt ......
    1 [23:20:26]
    2 [16:28:13]
    3 [16:29:17]
    .....
    8 [14:28:47]
    9 [12:09:51]
    Lnr | Time | Txt ......
    10 [12:11:03]
    .....
    #>
    
    
    

    • Marked as answer by
      arnold_
      Monday, March 10, 2014 3:45 PM

Introduction to Cells

In Microsoft Excel, a cell is nothing but an intersection of a column and a row. This cell is referenced by its row number and column letter. A cell can hold a formula/data directly. It can be formatted with font styles and colors or background colors too.

Example of a cell selected with its row number and column letter.

In the image above, cell B4 is selected. It is the intersection of row number “4” and column letter “B.” Since the value of the cell does not start with an “=”, it means that the cell is holding some data directly. Here the data held is “110.”

Empty Cells in Excel

If the cell does not have any value, it is said to be empty. There’s a chance that a cell has the same font color and background color, but with some data. In that case, it may look empty but actually isn’t. So, to find this, we have to select the cell and check the formula bar.

Example of a cell holding text in a white font.

Here the selected cell D9 looks blank but has a value “India.” It is not visible on the cell because the color of the font in that cell is white, which is equal to its background color.

ISBLANK Formula

Microsoft Excel offers a formula named ISBLANK which returns/provides a Boolean result stating whether the value of that cells is blank or not.

Syntax:

ISBLANK( <value> )

Where <value> can be a reference to a cell.

Example of ISBLANK formula in Excel with a FALSE Boolean value.
Example of ISBLANK formula in Excel with a TRUE Boolean value.

In the above images, the selected cells hold the formula as in the formula bar referring to the cells B7 (first image) and C8 (second image) respectively. The false and true values are returned depending on the values in the cells referred as parameters.

The selected cells hold the formula seen in the formula bar referring to the cells B7 (first image) and C8 (second image) respectively. The false and true values are returned depending on the values in the cells referred as parameters.

Range of Cells in Excel

In Excel a range is a set of continuous cells which can be a part of one or more columns or one or more rows or both. For example, in this image above Range(“A1:B12”) can be termed as a range.

Empty Cells in a Range

If there is a need to find the empty cells in a huge range of cells, it might be time consuming and tiring to select each cell and find this manually. 

VBA to Find Empty Cells

VBA offers an inbuilt function called “IsEmpty” to do this for us.

Syntax

<Var> = IsEmpty ( <expression> )

Where <var> is any Boolean variable that can hold the end result value  (return value) of the function and <expression> is any value that needs to be checked if empty.

For Example:

Select a Cell and Display if it is Empty

Sub empty_demo()

' select an empty cell
Cells(1, 5).Select

' display a msg to cross check if the selected cell is empty
MsgBox IsEmpty(Cells(1, 5).Value)

End Sub

Example of selecting an empty cell.

The same with a non-empty cell:

Sub empty_demo()

' select a non-empty cell
Cells(1, 1).Select

' display a msg to cross check if the selected cell is empty
MsgBox IsEmpty(Cells(1, 1).Value)

End Sub

Example of selecting a cell that is not empty.

Another Simple Program to Check if a Cell is Empty

Sub demo2()

' check if the value of a particular cell is nothing or ""
' if there is a value, the value is displayed . If not, a statement is displayed
If Cells(3, 4).Value = "" Then
    MsgBox "The cell in 3rd row and 4th col is empty"
Else
    MsgBox Cells(3, 4).Value
End If
End Sub

This program looks if the value of a specific cell is empty using just the “”. The same can also be done on several cells using a loop/range.

VBA – Find Empty Cells in a Range

It is possible to find the cells that are empty in a range of cells. Once a range is defined, we can loop through each cell in the range. As we loop, we can check if the cell is empty.

Program to Count the Number of Empty Cells in a Range of Cells

In this program:

  1. We declare a count variable and initialize it to “0.” This will help us count the number of empty cells in a range.
  2. We define a range in an Excel worksheet.
  3. Then we loop through the cells in it using a “for each” loop. Inside the loop, we check if the cell is empty/blank using the inbuilt VBA function “ISEMPTY()”.
  4. If so, the value of the “cnt” variable is incremented by “1.” Once we come out of the loop, we display the value of “cnt” as the number of empty cells in the declared range.
Sub empty_demo()

' declare a range
Dim myrange

'declare a variable to store count
Dim cnt

' define the range  and initialize count
myrange = Range("A1:A20")
cnt = 0

'loop through each cell of the range
For Each cell In myrange
    ' if the cell is empty , we increment the value of cnt variable by 1
    If IsEmpty(cell) Then
        cnt = cnt + 1
    End If
    
Next cell

' display the number of empty cells
MsgBox "There are " &amp;amp; cnt &amp;amp; " empty cells in the mentioned range. "

End Sub

Example of counting the number of empty cells in a range.

In our declared range, A14 to A20 are blank. The count is “7” that is displayed in a message box as per our code.

Color the Empty Cells in a Range of Cells Without Defining Any Range

In this program, instead of using a range, we use a nested “for loop” to iterate through every row in every column. The outer loop iterates through the columns while the inner loop iterates through the rows. The upper and lower bounds of the desired range/table are already provided in the “for loop” definition. Inside the inner loop, as in the previous example, we check if the cell is empty and add a number to the “cnt” variable’s value if so. Here, in addition, we also color those empty cells that are identified within the inner loop’s condition.

Sub empty_demo_1()

' declare variables to indicate, row, col and counter
Dim r, c, cnt

' intialize the variables
r = 1
c = 1
cnt = 0

' loop through each col in the worksheet till we reach col no "2"
For c = 1 To 2
' loop through each row in the worksheet till we reach row no "20"
For r = 1 To 20
' if the cell ( intersection of the row and col) is empty , we increment the value of cnt variable by 1
If IsEmpty(Cells(r, c).Value) = True Then
cnt = cnt + 1
' Color  the cells in yellow just to identify
Cells(r, c).Interior.Color = 65535
End If
Next r

Next c
' display the number of empty cells
MsgBox "There are " &amp;amp;amp; cnt &amp;amp;amp; " empty cells in the mentioned range. "

End Sub

Example of coloring empty cells without defining a range.

Using IsEmpty() for Variable Values

This program checks if a variable is empty and displays the result.

Sub demo3()

' declare a variable and do not initialize
Dim var1

' check if variable has value
If IsEmpty(var1) = True Then
' statement if empty
Debug.Print "Var1 is Empty"
Else
' statement if not empty
Debug.Print "Var1 has a value " &amp;amp;amp; var1
End If

End Sub

Output would be:

“Var1 is Empty”

Sub demo3()

' declare a variable and initialize it
Dim var1
var1 = "This is a good day"

' check if variable has value
If IsEmpty(var1) = True Then
' statement if empty
Debug.Print "Var1 is Empty"
Else
' statement if not empty
Debug.Print "Var1 has a value. " &amp;amp;amp; var1
End If

Output would be:

“Var1 has a value. This is a good day”

Conclusion

Apart from cells and variables, the IsEmpty() function offered by VBA can be used for arrays and many such objects. However, these are not elaborated here as the focus of this article is on checking if a cell is empty. The “” ( empty double quotes) can also be used to check if the cell(s) are empty. This is just a replacement for the IsEmpty() function and straightforward too. At times, we get stuck into a situation where nothing works out to validate if a cell is empty. In that case we can also try the len() function. The length of the cell value is “0” if it is actually empty. 

Check out our other articles on the specific functions to know much about their usage.

Tagged with: Cells and Ranges, empty cells, Excel, Formulas, Functions and Formulas, isempty, Loop, Microsoft Excel, Range, VBA, VBA Boolean, VBA For Excel

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.

  1. Start with the function name “IsEmpty”.
  2. Specify the cell that you want to check.
  3. Use a message box or a cell to get the result value.
  4. 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

    Понравилась статья? Поделить с друзьями:
  • Excel vba find не работает
  • Excel vba find найти все
  • Excel vba find если не находит
  • Excel vba find в строке
  • Excel vba find в диапазоне