Excel vba если диапазон пустой

Определение с помощью кода VBA Excel, что диапазон ячеек пуст, то есть, ни одна из ячеек диапазона (строки, столбца) не содержит отображаемого значения.

Определение пустого диапазона

Определить в VBA Excel, что диапазон ячеек пуст, можно с помощью функции рабочего листа WorksheetFunction.CountA или свойства диапазона ячеек Range.Text.

Пример 1

Определение, что диапазон ячеек пуст, с помощью функции рабочего листа WorksheetFunction.CountA:

Sub Primer1()

    If WorksheetFunction.CountA(Range(«A1:L8»)) = 0 Then

        MsgBox «Диапазон ячеек ««A1:L8»» пуст»

    Else

        MsgBox «Диапазон ячеек ««A1:L8»» не пуст»

    End If

End Sub

Функция WorksheetFunction.CountA подсчитывает количество ячеек, содержащих значения, в том числе нули и формулы, возвращающие пустые строки. Если хотя бы одна ячейка в диапазоне будет содержать пустую строку, возвращенную формулой, то код первого примера определит, что диапазон не пуст.

Пример 2

Определение, что диапазон ячеек пуст, с помощью свойства Text объекта Range:

Sub Primer2()

    If Range(«A1:L8»).Text = «» Then

        MsgBox «Диапазон ячеек ««A1:L8»» пуст»

    Else

        MsgBox «Диапазон ячеек ««A1:L8»» не пуст»

    End If

End Sub

Свойство Text объекта Range возвратит пустую строку только в том случае, если все ячейки диапазона будут содержать пустые строки и (или) значение Empty. Если одна или более ячеек в диапазоне будут содержать пустую строку, возвращенную формулой, то код второго примера все-равно определит, что диапазон пуст.

Определение пустой строки

Определение пустой строки в VBA Excel с помощью свойства Range.Text:

Sub Primer3()

    If Rows(5).Text = «» Then

        MsgBox «Указанная строка пуста»

    Else

        MsgBox «Указанная строка не пуста»

    End If

End Sub

Данное определение пустой строки используется в коде для удаления пустых строк из таблицы.

Определение пустого столбца

Определение пустого столбца в VBA Excel с помощью свойства Range.Text:

Sub Primer4()

    If Columns(7).Text = «» Then

        MsgBox «Указанный столбец пуст»

    Else

        MsgBox «Указанный столбец не пуст»

    End If

End Sub

или

Sub Primer5()

    If Columns(«G»).Text = «» Then

        MsgBox «Указанный столбец пуст»

    Else

        MsgBox «Указанный столбец не пуст»

    End If

End Sub


Фразы для контекстного поиска: диапазон пустой, строка пустая, столбец пустой.


Студворк — интернет-сервис помощи студентам

Такой вопрос:
есть такой код:

Visual Basic
1
2
3
4
Dim r As Range
With Sheets("data1").Columns(Target.Column - 1).Find(Target.Value, LookAt:=xlWhole)
Set r = Intersect(Sheets("data1").UsedRange, Sheets("data1").Range(.Item(1), .Item(1).End(xlDown))).Offset(, 1)
End With

На определенном этапе возникает ошибка object variable or with block variable not set на этой строке.

Visual Basic
1
Set r = Intersect(Sheets("data1").UsedRange, Sheets("data1").Range(.Item(1), .Item(1).End(xlDown))).Offset(, 1)

Понятия не имею что она означает.

Строка написана правильно. Ошибка возникает потому, что Intersect().Offset(,) равно нулю, пустоте и т.д.
Вопрос: Что это за строка и ошибка? Они у меня часто появляются… И можно ли написать условие, типа:

Visual Basic
1
2
3
4
5
Dim r As Range
With Sheets("data1").Columns(Target.Column - 1).Find(Target.Value, LookAt:=xlWhole)
 if Intersect(Sheets("data1").UsedRange, Sheets("data1").Range(.Item(1), .Item(1).End(xlDown))) Is Nothing Then Exit Sub
 Set r = Intersect(Sheets("data1").UsedRange, Sheets("data1").Range(.Item(1), .Item(1).End(xlDown))).Offset(, 1)
End With

Спасибо, заранее.

6 ответов

Нашел решение из комментариев, которые я получил.

Sub Empty()
    If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
        MsgBox "Empty"
    Else
        MsgBox "Not Empty"
    End If
End Sub

Kano
30 май 2012, в 07:17

Поделиться

IsEmpty возвращает True, если переменная не инициализирована или явно установлена ​​в Пустое; в противном случае он возвращает False. False всегда возвращается, если выражение содержит более одной переменной. IsEmpty только возвращает значимую информацию для вариантов. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx). Поэтому вы должны проверять каждую ячейку отдельно:

    Dim thisColumn as Byte, thisRow as Byte

    For thisColumn = 1 To 5
        For ThisRow = 1 To 6
             If IsEmpty(Cells(thisRow, thisColumn)) = False Then
                 GoTo RangeIsNotEmpty
             End If
        Next thisRow
    Next thisColumn
    ...........
    RangeIsNotEmpty: 

Конечно, здесь больше кода, чем в решении с функцией CountA, которые подсчитывают не пустые ячейки, но GoTo может перехватывать петли, если найдена хотя бы одна непустая ячейка и быстрее выполняет ваш код, особенно если диапазон большой, и вам нужно обнаружить Это дело. Также этот код для меня легче понять, что он делает, чем с функцией Excel CountA, которая не является функцией VBA.

Sharunas Bielskis
27 июнь 2016, в 13:26

Поделиться

Dim M As Range

    Set M = Selection

If application.CountIf(M, "<>0") < 2 Then
    MsgBox "Nothing selected, please select first BOM or Next BOM"
Else

'Your code here

End If

Из опыта, который я только что узнал, вы могли бы сделать:

If Selection.Rows.Count < 2 
Then End If`

Уточнение будет предоставлено немного позже (сейчас я работаю)

DeerSpotter
30 июль 2015, в 15:38

Поделиться

Если вы окажетесь в ситуации, когда абсолютно необходимо циклически проходить через каждую ячейку в диапазоне вместо использования CountA, тогда гораздо быстрее сначала преобразовать этот диапазон в массив и зациклить значения этого массива, чем зацикливать во многих диапазонах/клетки.

Function IsRangeEmpty(ByVal rng As Range) As Boolean

    'Converts a range to an array and returns true if a value is found in said array

    Dim area As Range
    For Each area In rng.areas

        Dim arr As Variant
        arr = area.value

        For i = LBound(arr, 2) To UBound(arr, 2)        'columns
            For j = LBound(arr, 1) To UBound(arr, 1)    'rows

                'if cell is not empty then
                If Len(Trim(arr(j, i))) > 0 Then
                    IsRangeEmpty = False
                    Exit Function
                End If

            Next j
        Next i

    Next area

    IsRangeEmpty = True

End Function

Пример того, как его использовать:

Sub Test()
    Debug.Print IsRangeEmpty(Range("A38:P38"))
End Sub

Если Range("A38:P38") пуст, будет напечатано True; иначе это напечатало бы False.

Marcucciboy2
07 нояб. 2018, в 20:11

Поделиться

Dim cel As Range, hasNoData As Boolean

    hasNoData = True
    For Each cel In Selection
        hasNoData = hasNoData And IsEmpty(cel)
    Next

Это вернет True если ни одна ячейка в Selection содержит каких-либо данных. Для определенного диапазона просто замените RANGE(...) на Selection.

TomM
04 май 2018, в 14:35

Поделиться

Другое возможное решение. Считайте пустые ячейки и вычтем это значение из общего числа ячеек

Sub Emptys()

Dim r As range
Dim totalCells As Integer

'My range To check'
Set r = ActiveSheet.range("A1:B5")

'Check for filled cells'
totalCells = r.Count- WorksheetFunction.CountBlank(r)


If totalCells = 0 Then
    MsgBox "Range is empty"
Else
    MsgBox "Range is not empty"
End If

End Sub

DJK
04 сен. 2017, в 02:27

Поделиться

Ещё вопросы

  • 1Есть ли какой-либо API для одновременного получения изображения как с задней, так и с передней камеры? [Дубликат]
  • 1Как правильно закрыть экземпляр Selenium WebDriver в python?
  • 1DataGridView: сортировка сначала по одному типу данных
  • 0Лучший способ реализации конфигурации для пользовательской директивы (ngIdle)?
  • 1Разрешения тестового приложения Android Integration
  • 1DataFrame Pandas объединяет неожиданные значения
  • 1иерархия рисования бумаги (элемент / путь)
  • 0JavaScript onkeypress отложенный триггер
  • 0Как я могу конвертировать Top: 50% в Top: 305px (или около того) с помощью JavaScript
  • 1Разбор XML в XFire вызывает высокую загрузку процессора?
  • 1get JSONException: значение типа java.lang.String не может быть преобразовано в JSONObject при анализе ответа JSON.
  • 0нг-если вызывается до того, как данные будут готовы с AngularJS
  • 1незагроможденная регистрация с помощью scala?
  • 0Если ставить на клик?
  • 1метод equals () класса Object
  • 0Запрос «SELECT * FROM… WHERE…» в PHP с запросом POST
  • 0Разыменование надстройки :: ptr_vector
  • 0Кэш Angular $ http провалил попытки?
  • 0Magento 1.9, я не могу получить сетку с проверенными продуктами
  • 0асинхронный обратный вызов: вложенные вызовы $ http.get
  • 1Чистый доступ к аспектам подкласса в статическом методе
  • 1Нумерация кроссворда Java ACM Graphics
  • 1вывод функции печати в csv в python
  • 0Как сделать так, чтобы элемент переключателя закрывался при его нажатии?
  • 1Радио кнопки с дат.гуи
  • 1рисование объектов формы в Java (перетаскиваемый, изменяемый размер и может вращаться)
  • 1Как получить дочерние папки проекта TFS с помощью TFS SDK
  • 0как добавить выпадающий список с использованием данных JSON stringify
  • 1сравнить две строки и назначить оценку в Python
  • 1Доступ к закрытой переменной в Java
  • 0Не удается получить значение параметра при использовании Angularjs
  • 0Как изменить переменную HTML в jQuery?
  • 1Как добавить свиток во Фрагмент
  • 0Написание XML-кода с цветовой кодировкой в HTML с тегом <span>, вызывающим пробелы
  • 1WPF XMLDataProvider не работает для объединения XPath
  • 1Изменить положение селектора управления листовкой
  • 1Функция палиндрома с петлей FOR
  • 1Назначенный ярлык для Android Studio не работает
  • 1Получение NameError в Python при получении данных в Jupyter
  • 1Узел JS crypto «Неверная строка ввода»
  • 0возьмите класс элемента и поместите его в другой элемент в качестве атрибута
  • 0Обновление в JPA без собственного запроса
  • 0preg_match_all: получить текст внутри кавычек, кроме HTML-тегов
  • 1Сущности, не появляющиеся в ЦезииJS
  • 0как читать только int и игнорировать остальное в C ++
  • 1Как ограничить устройство Android, чтобы не открывать какой-то конкретный сайт egyoutube, facebook
  • 0Cron Job (PHP) -> выбор записей следующего года не работает
  • 0невозможно отправить данные на веб-сервис через jquery
  • 1Рассчитать угол места между двумя точками широты / долготы / высоты, используя цезий

Содержание

  1. Excel Visual Basic — определить, если диапазон пуст
  2. 6 ответов
  3. Макрос определяющий пустая ли ячейка или заполненная в VBA Excel
  4. Алгоритм для строго определенной ячейки с применением её адреса.
  5. Алгоритм для выделенной (активной) ячейки :
  6. Еще один способ определения в примере для активной ячейки, но можно использовать и для конкретной ячейки с адресом.
  7. Добавить комментарий Отменить ответ
  8. Работа с диапазонами в VBA
  9. Копирование диапазона
  10. Запрос значения ячейки
  11. Ввод значения в следующую пустую ячейку
  12. Приостановка работы макроса для определения диапазона пользователем
  13. Подсчет выделенных ячеек
  14. Просмотр выделенного диапазона
  15. Дублирование строк
  16. Определение диапазона, находящегося в другом диапазоне
  17. Определение типа данных ячейки

Excel Visual Basic — определить, если диапазон пуст

Я не знаю, возможно ли это, но я хочу проверить, свободен ли диапазон в Excel. Итак, как мне написать, если:

Пусто в коде VBA?

6 ответов

Нашел решение из комментариев, которые я получил.

IsEmpty возвращает True, если переменная не инициализирована или явно установлена ​​в Пустое; в противном случае он возвращает False. False всегда возвращается, если выражение содержит более одной переменной. IsEmpty только возвращает значимую информацию для вариантов. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx). Поэтому вы должны проверять каждую ячейку отдельно:

Конечно, здесь больше кода, чем в решении с функцией CountA, которые подсчитывают не пустые ячейки, но GoTo может перехватывать петли, если найдена хотя бы одна непустая ячейка и быстрее выполняет ваш код, особенно если диапазон большой, и вам нужно обнаружить Это дело. Также этот код для меня легче понять, что он делает, чем с функцией Excel CountA, которая не является функцией VBA.

Из опыта, который я только что узнал, вы могли бы сделать:

Уточнение будет предоставлено немного позже (сейчас я работаю)

Если вы окажетесь в ситуации, когда абсолютно необходимо циклически проходить через каждую ячейку в диапазоне вместо использования CountA , тогда гораздо быстрее сначала преобразовать этот диапазон в массив и зациклить значения этого массива, чем зацикливать во многих диапазонах/клетки.

Пример того, как его использовать:

Если Range(«A38:P38») пуст, будет напечатано True ; иначе это напечатало бы False .

Это вернет True если ни одна ячейка в Selection содержит каких-либо данных. Для определенного диапазона просто замените RANGE(. ) на Selection .

Источник

Макрос определяющий пустая ли ячейка или заполненная в VBA Excel

Периодически при создании различных макросов в VBA Excel возникает потребность в том, чтобы алгоритм макроса самостоятельно определял, пуста ли ячейка или заполнена данными.

Далее приведем несколько простых макросов для определения заполнения ячейки данными и разберем принцип их работы. Фрагменты этих макросов вы можете добывать в свой код для реализации проверки заполнения ячеек.

Рассмотрим несколько вариантов VBA алгоритмов:

Алгоритм для строго определенной ячейки с применением её адреса.

Пример для ячейки с адресом B6:

  • Private Sub CommandButton1_Click() ‘наименование алгоритма
  • If IsEmpty(Range(«B6»)) = True Then ‘условие, если ячейка пустая, то
  • MsgBox («В ячейке нет данных») ‘вывод сообщения, что в ячейке нет данных
  • Else ‘в противном случае
  • MsgBox («Данные внесены в ячейку») ‘вывод сообщения, что в ячейке есть данные
  • End If ‘конец блока «если»
  • End Sub ‘конец алгоритма

Алгоритм для выделенной (активной) ячейки :

  • Private Sub CommandButton1_Click() ‘наименование алгоритма
  • If IsEmpty(ActiveCell) = True Then ‘условие, если активная ячейка (ActiveCell) пустая, то
  • MsgBox («В ячейке нет данных») ‘вывод сообщения, что в ячейке нет данных
  • Else ‘в противном случае
  • MsgBox («Данные внесены в ячейку») ‘вывод сообщения, что в ячейке есть данные
  • End If ‘конец блока «если»
  • End Sub ‘конец алгоритма

Еще один способ определения в примере для активной ячейки, но можно использовать и для конкретной ячейки с адресом.

  • Private Sub CommandButton1_Click() ‘наименование алгоритма
  • If Len(ActiveCell) Then ‘если активная ячейка заполнена данными (имеет объем информации)
  • MsgBox («Данные внесены в ячейку») ‘вывод сообщения, что в ячейке есть данные
  • Else ‘в противном случае
  • MsgBox («Ячейка пустая») ‘вывод сообщения, что в ячейке нет данных
  • End If ‘конец блока «если»
  • End Sub ‘конец алгоритма

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

Работа с диапазонами в VBA

Настоящая заметка продолжает знакомство с VBA, в ней описана работа с диапазонами в VBA.[1]

Рис. 1. Пример, демонстрирующий, как выделять диапазоны различной формы в VBA$ чтобы увеличить изображение кликните на нем правой кнопкой мыши и выберите Открыть картинку в новой вкладке

Скачать заметку в формате Word или pdf, примеры в архиве (политика безопасности провайдера не позволяет загружать файлы Excel с поддержкой макросов)

Копирование диапазона

Функция записи макросов Excel используется не столько для создания хорошего кода, сколько для поиска названий необходимых объектов, методов и свойств. Например, при записи операции копирования и вставки можно получить код:

Sub Макрос()
Range( » A1 » ).Select
Selection.Copy
Range( » B1 » ).Select
ActiveSheet.Paste
End Sub

Обратите внимание, что данная программа выделяет ячейки. Однако в VBA для работы с объектом не обязательно его выделять. Данную процедуру можно заменить значительно более простой — применить метод Сору, который использует аргумент, представляющий адрес места вставки копируемого диапазона.

Sub CopyRange()
Range( » А1 » ).Copy Range( » В1 » )
End Sub

Предполагается, что рабочий лист является активным и операция выполняется на активном рабочем листе. Чтобы скопировать диапазон на другой рабочий лист или в другую книгу, необходимо задать ссылку:

Sub CopyRange2()
Workbooks( » File1.xlsx » ).Sheets( » Лист1 » ).Range( » A1 » ).Copy _
Workbooks( » File2.xlsx » ).Sheets( » Лист2 » ).Range( » A1 » )
End Sub

Еще одним подходом к решению этой задачи является использование для представления диапазонов объектных переменных:

Sub CopyRange3()
Dim Rngl As Range, Rng2 As Range
Set Rngl = Workbooks( » File1.xlsx » ).Sheets( » Лист1 » ).Range( » A1 » )
Set Rng2 = Workbooks( » File2.xlsx » ).Sheets( » Лист2 » ).Range( » A1 » )
Rngl.Copy Rng2 End Sub

Можно копировать большой диапазон. Адрес места вставки определяется единственной ячейкой (представляющей верхний левый угол вставляемого диапазона):

Sub CopyRange4 ()
Range( » А1:С800 » ).Copy Range( » D1 » )
End Sub

Для перемещения диапазона ячеек вместо метода Сору используется метод Cut.

Если размер копируемого диапазона не известен используется свойство CurrentRegion, возвращающее объект Range, который соответствует прямоугольнику ячеек вокруг заданной ячейки:

Sub CopyCurrentRegion2()
Range( » A1 » ).CurrentRegion.Copy Sheets( » Лист2 » ).Range( » A1 » )
End Sub

Метод End имеет один аргумент, определяющий направление, в котором увеличивается выделение ячеек. Следующий оператор выделяет диапазон от активной ячейки до последней непустой ячейки внизу:

Range (ActiveCell, ActiveCell.End(xlDown)).Select

Три остальные константы имитируют комбинации клавиш при выделении в других направлениях: xlUp (вверх), xlToLeft (влево) и xlToRight (вправо).

В прилагаемом Excel-файле определено несколько распространенных типов выделения ячеек (см. рис. 1). Код любопытен тем, что является также примером создания контекстного меню.

Запрос значения ячейки

Следующая процедура запрашивает значение у пользователя и вставляет его в ячейку А1:

Sub GetValuel()
Range( » A1 » ).Value = InputBox( » Введите значение » )
End Sub

Однако при выполнении этой процедуры возникает проблема. Если пользователь щелкнет на кнопке Отмена в окне ввода данных, то процедура удалит данные, которые находились в текущей ячейке. Модифицированная версия процедуры адекватно реагирует на щелчок на кнопке Отмена и не выполняет при этом никаких действий:

Sub GetValue2()
Dim UserEntry As Variant
UserEntry = InputBox( » Введите значение » )
If UserEntry <> » » Then Range( » A1 » ).Value = UserEntry
End Sub

Во многих случаях следует проверить правильность данных, введенных пользователем. Например, необходимо обеспечить введение только чисел в диапазоне от 1 до 12 (рис. 2). Это можно сделать при помощи процедуры GetValue3(), код которой приведен в Модуле1 приложенного Excel-файла. Некорректные данные игнорируются, и окно запроса значения отображается снова. Этот цикл будет повторяться, пока пользователь не введет правильное значение или не щелкнет на кнопке Отмена.

Рис. 2. Проверка данных, введенных пользователем

Ввод значения в следующую пустую ячейку

Если требуется ввести значение в следующую пустую ячейку столбца или строки, используйте код (рис. 3):

Sub GetData()
Dim NextRow As Long
Dim Entry1 As String, Entry2 As String
Do
‘ Определение следующей пустой строки
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
‘ Запрос данных
Entry1 = InputBox( » Введите имя » )
If Entry1 = » » Then Exit Sub
Entry2 = InputBox( » Введите сумму » )
If Entry2 = » » Then Exit Sub
‘ Запись данных
Cells(NextRow, 1) = Entry1
Cells(NextRow, 2) = Entry2
Loop
End Sub

Рис. 3. Макрос вставляет данные в следующую пустую строку рабочего листа

Это бесконечный цикл. Для выхода из него (щелкните на кнопке Cancel) использовались операторы Exit Sub. Обратите внимание строку, в который определяется значение переменной NextRow. Если вам трудно ее понять, проанализируйте содержимое ячейки: перейдите в последнюю ячейку столбца А и нажмите и . После этого будет выделена последняя непустая ячейка в столбце А. Свойство Row возвращает номер этой строки; чтобы получить расположенную под ней строку (следующую пустую строку), к этому номеру прибавляется 1.

Приостановка работы макроса для определения диапазона пользователем

В некоторых ситуациях макрос должен взаимодействовать с пользователем. Например, можно создать макрос, который приостанавливается, когда пользователь указывает диапазон ячеек. Для этого воспользуйтесь функцией Excel InputBox. Не путайте метод Excel InputBox с функцией VBA InputBox. Несмотря на идентичность названий, это далеко не одно и то же.

Процедура, представленная ниже, демонстрирует, как приостановить макрос и разрешить пользователю выбрать ячейку. Затем автоматически формула вставляется в каждую ячейку выделенного диапазона.

Sub GetUserRange()
Dim UserRange As Range
Prompt = » Выберите диапазон для случайных чисел. »
Title = » Выбор диапазона »
‘ Отображение поля ввода
On Error Resume Next
Set UserRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=ActiveCell.Address, _
Type:=8) ‘ Выделение диапазона
On Error GoTo 0
‘ Отменено ли отображение поля ввода?
If UserRange Is Nothing Then
MsgBox » Отменено. »
Else
UserRange.Formula = » =RAND() »
End If
End Sub

Окно ввода данных показано на рис. 4. Важный момент в этой процедуре – определение аргумента Туре равным 8 (в этом случае InputBox вернет диапазон; подробнее см. Application.InputBox Method).

Рис. 4. Использование окна ввода данных с целью приостановки выполнения макроса

Оператор On Error Resume Next игнорирует ошибку, если пользователь не выберет диапазон, а щелкает Отмена. В таком случае объектная переменная UserRange не получает значения. В этом случае отобразится окно сообщения с текстом «Отменено». Если же пользователь щелкнет на кнопке OK, то макрос продолжит выполняться. Строка On Error Go То указывает на переход к стандартной обработке ошибки. Проверка корректного выделения диапазона необязательна. Excel позаботится об этом вместо вас.

Обязательно проверьте, включено ли обновление экрана при использовании метода InputBox для выделения диапазона. Если обновление экрана отключено, вы не сможете выделить рабочий лист. Чтобы проконтролировать обновление экрана, в процессе выполнения макроса используйте свойство ScreenUpdating объекта Application.

Подсчет выделенных ячеек

Работая с макросом, который обрабатывает выделенный диапазон ячеек, можно использовать свойство Count, чтобы определить, сколько ячеек содержится в выделенном (или любом другом) диапазоне. Например, оператор MsgBox Selection.Count демонстрирует окно сообщения, которое отображает количество ячеек в текущем выделенном диапазоне. Свойство Count использует тип данных Long, поэтому наибольшее значение, которое может храниться в нем, равно 2 147 483 647. Если выделить лист целиком, то ячеек будет больше, и свойство Count сгенерирует ошибку. Используйте свойство CountLarge, которое не имеет таких ограничений.

Если активный лист содержит диапазон data, то следующий оператор присваивает количество ячеек в диапазоне data переменной с названием CellCount:

CellCount = Range( » data » ).Count

Вы можете также определить, сколько строк или столбцов содержится в диапазоне. Следующее выражение вычисляет количество столбцов в выделенном диапазоне:

Следующий оператор пересчитывает количество строк в диапазоне с названием data и присваивает это количество переменной RowCount.

RowCount = Range( » data » ).Rows.Count

Просмотр выделенного диапазона

Вы можете столкнуться с трудностями при создании макроса, который оценивает каждую ячейку в диапазоне и выполняет операцию, определенную заданному критерию. Если выделен целый столбец или строка, то работа макроса может занять много времени. Процедура ColorNegative устанавливает красный цвет для ячеек, которые содержат отрицательные значения. Цвет фона для других ячеек не определяется. Код процедуры можно найти в Модуле4 приложенного Excel-файла.

Усовершенствованная процедура ColorNegative2, создает объектную переменную WorkRange типа Range, которая представляет собой пересечение выделенного диапазона и диапазона рабочего листа (рис. 5). Если выделить столбец F (1048576 ячеек), то его пересечение с рабочим диапазоном В2:I16) даст область F2:F16, которая намного меньше исходного выделенного диапазона. Время, затрачиваемое на обработку 15 ячеек, намного меньше времени, уходящего на обработку миллиона ячеек.

Рис. 5. В результате пересечения используемого диапазона и выделенного диапазона рабочего листа уменьшается количество обрабатываемых ячеек

И всё же процедура ColorNegative2 недостаточно эффективна, поскольку обрабатывает все ячейки в диапазоне. Поэтому предлагается процедура ColorNegative3. В ней используется метод SpecialCells, с помощью которого генерируются два поднабора выделенной области: один поднабор (ConstantCells) включает ячейки, которые содержат исключительно числовые константы; второй поднабор (FormulaCells) включает ячейки, содержащие числовые формулы. Обработка ячеек в этих поднаборах осуществляется с помощью двух конструкций For Each-Next. Благодаря тому, что исключается обработка пустых и нетекстовых ячеек, скорость выполнения макроса существенно увеличивается.

Sub ColorNegative3()
‘ Окрашивание ячеек с отрицательными значениями в красный цвет
Dim FormulaCells As Range, ConstantCells As Range
Dim cell As Range
If TypeName(Selection) <> » Range » Then Exit Sub
Application.ScreenUpdating = False
‘ Создание поднаборов исходной выделенной области
On Error Resume Next
Set FormulaCells = Selection.SpecialCells(xlFormulas, xlNumbers)
Set ConstantCells = Selection.SpecialCells(xlConstants, xlNumbers)
On Error GoTo 0
‘ Обработка ячеек с формулами
If Not FormulaCells Is Nothing Then
For Each cell In FormulaCells
If cell.Value ‘ Обработка ячеек с константами
If Not ConstantCells Is Nothing Then
For Each cell In ConstantCells
If cell.Value » Пустые строки удалены. »
End Sub

Первый шаг — определить последнюю используемую строку и присвоить этот номер строки переменной LastRow. Это не так просто, как можно ожидать, поскольку текущий диапазон необязательно начинается со строки 1. Следовательно, значение LastRow вычисляется таким образом: к найденному количеству строк используемого диапазона прибавляется номер первой строки текущего диапазона и вычитается 1.

В процедуре применена функция Excel СЧЁТЗ, определяющая, является ли строка пустой. Если данная функция для конкретной строки возвращает 0, то эта строка пустая. Обратите внимание, что процедура просматривает строки снизу вверх и использует отрицательное значение шага в цикле For-Next. Это необходимо, поскольку при удалении все последующие строки перемещаются «вверх» в рабочем листе. Если бы в цикле просмотр выполнялся сверху вниз, то значение счетчика цикла после удаления строки оказалось бы неправильным.

В макросе используется еще одна переменная, Counter, с помощью которой подсчитывается количество удаленных строк. Эта величина отображается в окне сообщения по завершении процедуры.

Дублирование строк

Пример, рассматриваемый в этом разделе, демонстрирует использование возможностей VBA для создания дубликатов строк. На рис. 6 показан пример рабочего листа, используемого организаторами лотереи. В столбце А вводится имя. В столбце В содержится количество лотерейных билетов, приобретенных одним покупателем. В столбце С находится случайное число сгенерированное с помощью функции СЛЧИС. Победитель определяется путем сортировки данных в третьем столбце (выигрыш соответствует наибольшему случайному числу).

Рис. 6. Дублирование строк на основе значений в столбце В

А теперь нужно продублировать строки, в результате чего количество строк для каждого участника лотереи будут соответствовать количеству купленных им билетов. Например, если Барбара приобрела два билета, для нее создаются две строки. Ниже показана процедура, выполняющая вставку новых строк.

Sub DupeRows()
Dim cell As Range
‘ 1-я ячейка, содержащая сведения о количестве билетов
Set cell = Range( » B2 » )
Do While Not IsEmpty(cell)
If cell > 1 Then
Range(cell.Offset(1, 0), cell.Offset(cell.Value _
— 1,0)).EntireRow.Insert
Range(cell, cell.Offset(cell.Value — 1, — 1)). _
EntireRow.FillDown
End If
Set cell = cell.Offset(cell.Value, 0)
Loop
End Sub

Объектная переменная cell была инициализирована ячейкой В2, первой ячейкой, в которой находится числовая величина. Вставка новых строк осуществляется в цикле, а их копирование происходит с помощью метода FillDown. Значение переменной cell увеличивается на единицу, после чего выбирается следующий участник лотереи, Цикл выполняется до тех пор, пока не встретится пустая ячейка. На рис. 7 показан рабочий лист после выполнения этой процедуры.

Рис. 7. В соответствии со значением в столбце В добавлены новые строки

Определение диапазона, находящегося в другом диапазоне

Функция InRange имеет два аргумента, оба — объекты Range. Функция возвращает значение True (Истина), если первый диапазон содержится во втором.

Function InRange(rng1, rng2) As Boolean
‘ Возвращает True, если rng1 является подмножеством rng2
InRange = False
If rng1.Parent.Parent.Name = rng2.Parent.Parent.Name Then
If rng1.Parent.Name = rng2.Parent.Name Then
If Union(rng1, rng2).Address = rng2.Address Then
InRange = True
End If
End If
End If
End Function

Возможно, функция InRange кажется сложнее, чем того требует ситуация, поскольку в коде должна быть реализована проверка принадлежности двух диапазонов одной и той же книге и рабочему листу. Обратите внимание, что в процедуре используется свойство Parent, которое возвращает объект-контейнер заданного объекта. Например, следующее выражение возвращает название листа для объекта rng1:

Следующее выражение возвращает название рабочей книги rng1:

Функция VBA Union возвращает объект Range, который представляет собой объединение двух объектов типа Range. Объединение содержит все ячейки, относящиеся к исходным диапазонам. Если адрес объединения двух диапазонов совпадает с адресом второго диапазона, первый диапазон входит в состав второго диапазона.

Определение типа данных ячейки

В состав Excel входит ряд встроенных функций, которые могут помочь определить тип данных, содержащихся в ячейке. Это функции ЕНЕТЕКСТ, ЕЛОГИЧ и ЕОШИБКА. Кроме того, VBA поддерживает функции IsEmpty, IsDate и IsNumeric.

Ниже описана функция CellType, которая принимает аргумент-диапазон и возвращает строку, описывающую тип данных левой верхней ячейки этого диапазона (рис. 8). Такую функцию можно использовать в формуле рабочего листа или вызвать из другой процедуры VBA.

Рис. 8. Функция CellType, возвращающая тип данных ячейки

Function CellType(Rng)
‘ Возвращает тип ячейки, находящейся в левом верхнем углу диапазона
Dim TheCell As Range
Set TheCell = Rng.Range( » A1 » )
Select Case True
Case IsEmpty(TheCell)
CellType = » Пустая »
Case TheCell.NumberFormat = » @ »
CellType = » Текст »
Case Application.IsText(TheCell)
CellType = » Текст »
Case Application.IsLogical(TheCell)
CellType = » Логический »
Case Application.IsErr(TheCell)
CellType = » Ошибка »
Case IsDate(TheCell)
CellType = » Дата »
Case InStr(1, TheCell.Text, » : » ) <> 0
CellType = » Время »
Case IsNumeric(TheCell)
CellType = » Число »
End Select
End Function

Обратите внимание на использование оператора SetTheCell. Функция CellType получает аргумент-диапазон произвольного размера, но этот оператор указывает, что функция оперирует только левой верхней ячейкой диапазона (представленной переменной TheCell).

Источник

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.

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 если выполняется условие
  • Excel vba заливка диапазона ячеек
  • Excel vba если в ячейке дата
  • Excel vba закрыть не активную книгу без сохранения
  • Excel vba закрыть другую книгу