Как найти пустые ячейки в excel vba

 

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

 

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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 
 
 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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, если они пустые — залить эту ячейку красным цветом. Если в ней есть что-то , пропустить. Если во всех ячейках есть данные, то просто прекратить выполнение макроса без вывода сообщения.
Спасибо  

 

Юрий М

Модератор

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

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

 

Max.il

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

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

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

 

Юрий М

Модератор

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

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

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

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

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

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

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

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

 

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

 

БМВ

Модератор

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

Excel 2013, 2016

#19

17.12.2021 14:19:40

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

докажите.

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

 

Jack Famous

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

Сообщений: 10852
Регистрация: 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 ……., где К — переменная

И где К? )

Be it for troubleshooting formula errors or data integrity, you might find yourself trying to identify those cells going through the entire workbook. In this article we’re going to show to find in Excel if cell is blank using VBA and automate this process.

How to find in Excel if cell is blank using VBA

VBA has some predefined types for the cells that contains special values. These can be accessed with the SpecialCells method. The SpecialCells method uses two arguments to specify the cells; Type and Value. Using a combination of these two arguments you can easily access the cell or range type you desired. Below is a list of values both arguments can get.

Type

  • xlCellTypeAllFormatConditions. Cells of any format
  • xlCellTypeAllValidation. Cells having validation criteria
  • xlCellTypeBlanks. Empty cells
  • xlCellTypeComments. Cells containing comments
  • xlCellTypeConstants. Cells containing constants
  • xlCellTypeFormulas. Cells containing formulas
  • xlCellTypeLastCell. The last cell in the selected range. Note that this will include empty cells that have had any cells that changed from their default format.
  • xlCellTypeSameFormatConditions. Cells having the same format
  • xlCellTypeSameValidation. Cells having the same validation criteria
  • xlCellTypeVisible. All visible cells

Value

  • xlErrors
  • xlLogical
  • xlNumbers
  • xlTextValues

To find the blank cells using VBA, using xlCellTypeBlanks constant for the type argument is enough. The value argument can be omitted.

An important point in here is that the Selection.SpecialCells(xlCellTypeBlanks).Cells returns an array of cells. So, before returning any information, we need to step through each cell in the array. A For Each…Loop is perfect for arrays consisting of objects. We designed our code to return the address of all blank cells in a Message Box.

To be able to run codes, you need to add a module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.

Find blank cells

Sub FindBlankCells()

    Dim rng As Range, message As String

    For Each rng In Selection.SpecialCells(xlCellTypeBlanks).Cells

        message = message & Chr(10) & rng.Address 'Chr(10) is for new line

    Next

    MsgBox message, vbOKOnly, "Empty Cells" 'vbOKOnly is the type of the message box

End Sub

Via VBA how can I check if a cell is empty from another with specific information?

For example:

If A:A = «product special» And B:B is null Then

C1 = «product special»

Illustration of example

Additionally, how can I use a For Each loop on theRange and how can I return the value in the other cell?

Zoe stands with Ukraine's user avatar

asked Nov 13, 2012 at 12:19

Regis Santos's user avatar

Regis SantosRegis Santos

3,3998 gold badges41 silver badges64 bronze badges

0

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

Zoe stands with Ukraine's user avatar

answered Nov 13, 2012 at 12:40

Sylca's user avatar

1

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it’s not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

answered Nov 13, 2012 at 12:52

Deafdan's user avatar

DeafdanDeafdan

3932 silver badges13 bronze badges

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort.
In the second step, all rows with same data will be removed.

answered Nov 13, 2012 at 12:23

Reporter's user avatar

ReporterReporter

3,8495 gold badges32 silver badges46 bronze badges

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

    Определение с помощью кода 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


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


    Понравилась статья? Поделить с друзьями:
  • Как найти пустую ячейку в excel макрос
  • Как найти пустую строку в таблице excel
  • Как найти проценты от суммы формула excel
  • Как найти проценты в таблице excel
  • Как найти процентную ставку по кредиту в excel