Excel vba if cell not in range

In Microsoft Excel, we can determine if a Cell is within a Range with IF Function, however, when it comes to identify the same via VBA code then we need to use if statement. Below is the VBA code and process which you need to paste in the code module of your file.

1. Open Excel
2. Press ALT + F11
3. The VBA Editor will open.
4. Click anywhere in the Project Window.
5. Click on Insert
6. Click on Module

Image1

7. In the Code Window, Copy and Paste the below mentioned Code

Function InRange(Range1 As Range, Range2 As Range) As Boolean
‘ returns True if Range1 is within Range2
Dim InterSectRange As Range
Set InterSectRange = Application.InterSect(Range1, Range2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
End FunctionSub TestInRange()
If InRange(ActiveCell, Range(«A1:D100»)) Then
‘ code to handle that the active cell is within the right range
MsgBox «Active Cell In Range!»»»
Else
‘ code to handle that the active cell is not within the right range
MsgBox «Active Cell NOT In Range!»»»
End If
End Sub

you22

8. Once this is pasted, go to the Excel file
9. Select cell A1
10. Click on the VIEW Tab on the ribbon
11. Click on Macros
12. Click on View Macros
13. Shortcut Key to View Macros is ALT + F8
14. A Window will popup

you33

15. Select the Macro
16. Here the Macro is named as “TestInRange”
17. Select the Macro “TestInRange”
18. Click on Run
19. As this cell is in Range you will get a Popup which says “Active Cell In Range!”

image4

20. Click OK to close the Box

Now we will select Cell G9 which is not in Range

1. Select cell G9
2. Click on the VIEW Tab on the ribbon
3. Click on Macros
4. Click on View Macros
5. Shortcut Key to View Macros is ALT + F8
6. A Window will popup

yo55

7. Select the Macro
8. Here the Macro is named as “TestInRange”
9. Select Macro “TestInRange”
10. Click on Run
11. As this cell is not in Range you will get a Popup which says “Active Cell NOT In Range!”

image6

12. Click OK to close the Box

This is how we can determine whether a Cell is within a Range or not using VBA.

image 48

VBA that checks if a cell is in a range, named range, or any kind of range, in Excel.

ab8ca0d4d1e3775d79e3940a9f28a0cf.jpg

Sections:

Check if Cell is in a Range Macro

Check if Cell is in a Named Range

Notes

Check if Cell is in a Range Macro

Sub CellinRange()

'######################################'
'#########   TeachExcel.com   #########'
'######################################'

'Tests if a Cell is within a specific range.

Dim testRange As Range
Dim myRange As Range

'Set the range
Set testRange = Range("B3:D6")

'Get the cell or range that the user selected
Set myRange = Selection

'Check if the selection is inside the range.
If Intersect(testRange, myRange) Is Nothing Then
    'Selection is NOT inside the range.

    MsgBox "Selection is outside the test range."

Else
    'Selection IS inside the range.

    MsgBox "Selection is inside the test range."

End If

End Sub

How to Use the Macro

B3:D6 change this to the range that you want to check to see if the cell is within it.

Selection keep this the same to use the currently selected cell or range from the user or change it to a regular hard-coded range reference like Range(«A1») or whatever range you want.

‘Selection is NOT inside the range. under this line, put the code that you want to run when the cell is not within the range.

‘Selection IS inside the range. under this line, put the code that you want to run when the cell is within the range.

How Does the Macro Know if the Cell is in the Range?

Intersect(testRange, myRange) this checks if the range within the myRange variable overlaps or intersects with the range in the testRange variable. This function, the Intersect function, will return a range object where the two ranges overlap, or, if they don’t overlap, it will return nothing.

As such, we can use the IF statement to check if nothing was returned or not and we do that using Is Nothing after the Intersect function. The Is Nothing is what checks if the Intersect function returned nothing or not, which evaluates to TRUE or FALSE, which is then used by the IF statement to complete its logic and run.

This is how we get the full first line of the IF statement, and this is where all the magic happens:

If Intersect(testRange, myRange) Is Nothing Then

The rest of the IF statement is just a regular IF statement in VBA, with a section of code that runs if the cell is within the range and one that runs when the cell is outside of the range.

Check if Cell is in a Named Range

This is almost exactly the same as the previous macro except that we need to change the range reference from B3:D6 to the name of the named range; that’s it.

It could look like this:

Sub CellinRange()

'######################################'
'#########   TeachExcel.com   #########'
'######################################'

'Tests if a Cell is within a specific range.

Dim testRange As Range
Dim myRange As Range

'Set the range
Set testRange = Range("MyNamedRange")

'Get the cell or range that the user selected
Set myRange = Selection

'Check if the selection is inside the range.
If Intersect(testRange, myRange) Is Nothing Then
    'Selection is NOT inside the range.

    MsgBox "Selection is outside the test range."

Else
    'Selection IS inside the range.

    MsgBox "Selection is inside the test range."

End If

End Sub

For a more detailed expanation of how this macro works, look to the section above.

Notes

If the user makes a selection of multiple cells or a range, and any of those cells are within the test range, this macro will run the code for when the selection is inside the range.

Testing if a range is within a range simply uses the Intersect function in Excel VBA; however, due to how it works, it can seem confusing since we have to check if it Is Nothing or not. But, once you get used to writing this and seeing this in IF statements, it’s really not that difficult, just remember that, in this instance, you will want to pair the use of Intersect with Is Nothing and everything else should follow quite easily.

Download the sample file to get the macro in Excel.

Similar Content on TeachExcel

Excel Data Validation — Limit What a User Can Enter into a Cell

Tutorial:
Data Validation is a tool in Excel that you can use to limit what a user can enter into a…

Logical Operators in Excel VBA Macros

Tutorial: Logical operators in VBA allow you to make decisions when certain conditions are met.
They…

Make a UserForm in Excel

Tutorial: Let’s create a working UserForm in Excel.
This is a step-by-step tutorial that shows you e…

Sum Values that Equal 1 of Many Conditions across Multiple Columns in Excel

Tutorial:
How to Sum values using an OR condition across multiple columns, including using OR with …

VBA Comparison Operators

Tutorial: VBA comparison operators are used to compare values in VBA and Macros for Excel.
List of V…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

EXPLANATION

This tutorial shows how to test if a range does not contain a specific value and return a specified value if the formula tests true or false, by using an Excel formula and VBA.

This tutorial provides one Excel method that can be applied to test if a range does not contain a specific value and return a specified value by using an Excel IF and COUNTIF functions. In this example, if the Excel COUNTIF function returns a value of 0, meaning the range does not have cells with a value of 505, the test is TRUE and the formula will return a «Not in Range» value. Alternatively, if the Excel COUNTIF function returns a value of greater than 0, meaning the range has cells with a value of 505, the test is FALSE and the formula will return a «In Range» value.

This tutorial provides one VBA method that can be applied to test if a range does not contain a specific value and return a specified value and return a specified value.

FORMULA
=IF(COUNTIF(range, value)=0, value_if_true, value_if_false)

ARGUMENTS
range: The range of cells you want to count from.
value: he value that is used to determine which of the cells should be counted, from a specified range, if the cells’ value is equal to this value.
value_if_true: Value to be returned if the range does not contains the specific value.
value_if_false: Value to be returned if the range contains the specific value.

 

Подскажите как при помощи 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 ……., где К — переменная

И где К? )

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

    Skip to content

    VBA code to check if a cell is blank

    Home » VBA » VBA code to check if a cell is blank

    We can use VBA to check if a cell is blank and run the remaining statements. Sometimes, we need to determine and make sure a particular range is not empty before proceeding to the next statements. This example will help you to know how to check if a cell or a range is blank or not using Excel VBA. This can be used in Excel 2003,2007,2010,2013.

    VBA code to check if a cell is blank – Syntax

    Here is the example Excel VBA Syntax to check if a cell is blank or not. The below macro will check whether a Range A1 is blank or not.

    If Cells(1, 1) = "" Then
     ... Statements to execute if the Cell is Empty 
    Else
     ...statements to execute if Cell is not Blank.
    end if
    

    VBA code to check if a cell is blank – Example

    Here is the example macro to check if a cell is blank or not. The below macro will show a message box based on the Cell.

    Sub vba_code_to_check_if_a_cell_is_blank()
        If Cells(1, 1) = "" Then
            MsgBox "Cell is Blank"
        Else
            MsgBox "Cell is not blank"
        End If
    End Sub
    

    VBA code to check if a cell is blank – Better Example: Avoid Empty Spaces

    Sometimes, A cell or rang looks blank and we notice that the condition is failing. It is because of the empty spaces in the cell. So, whenever you want to check if a cell is empty, you can trim the Cell value and check it.

    Sub vba_code_to_check_if_a_cell_is_blank()
         'use trim to avoide blank spaces
        If Trim(Cells(1, 1)) = "" Then
            MsgBox "Cell is Blank"
        Else
            MsgBox "Cell is not blank"
        End If
    End Sub
    

    VBA code to check if a cell is blank – Instructions

    Please follow the below step by step instructions to test this Example VBA Macro codes:

    • Step 1: Open a New Excel workbook
    • Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
    • Step 3: Insert a code module from then insert menu of the VBE
    • Step 4: Copy the above code and paste in the code module which have inserted in the above step
    • Step 5: Enter some sample data at range A1 to check if the cell is blank or not using VBA.
    • Step 6: Now press F5 to execute the code or F8 to debug the Macro to check the if Range A1 is blank or not
    Effortlessly Manage Your Projects and Resources
    120+ Professional Project Management Templates!

    A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

    Save Up to 85% LIMITED TIME OFFER
    Excel VBA Project Management Templates
    All-in-One Pack
    120+ Project Management Templates
    Essential Pack
    50+ Project Management Templates

    Excel Pack
    50+ Excel PM Templates

    PowerPoint Pack
    50+ Excel PM Templates

    MS Word Pack
    25+ Word PM Templates

    Ultimate Project Management Template

    Ultimate Resource Management Template

    Project Portfolio Management Templates

    Related Posts

    VBA Reference

    Effortlessly
    Manage Your Projects

    120+ Project Management Templates

    Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

    120+ PM Templates Includes:
    By PNRaoLast Updated: January 19, 2015Categories: VBA

    One Comment

    1. Jorge Cabral
      March 12, 2017 at 6:01 AM — Reply

      What about if the cell as a formula, but the result is ” or zero?

    Effectively Manage Your
    Projects and  Resources

    With Our Professional and Premium Project Management Templates!

    ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

    We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

    Project Management
    Excel VBA

    Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

    Analysistabs Logo

    Page load link

    Go to Top

    “It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle

    This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

    Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.

    A Quick Guide to Ranges and Cells

    Function Takes Returns Example Gives

    Range

    cell address multiple cells .Range(«A1:A4») $A$1:$A$4
    Cells row, column one cell .Cells(1,5) $E$1
    Offset row, column multiple cells Range(«A1:A2»)
    .Offset(1,2)
    $C$2:$C$3
    Rows row(s) one or more rows .Rows(4)
    .Rows(«2:4»)
    $4:$4
    $2:$4
    Columns column(s) one or more columns .Columns(4)
    .Columns(«B:D»)
    $D:$D
    $B:$D

    Download the Code

     

    The Webinar

    If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.

    (Note: Website members have access to the full webinar archive.)

    vba ranges video

    Introduction

    This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.

     
    Generally speaking, you do three main things with Cells

    1. Read from a cell.
    2. Write to a cell.
    3. Change the format of a cell.

     
    Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion

    In this post I will tackle each one, explain why you need it and when you should use it.

     
    Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.

    Important Notes

    I have recently updated this article so that is uses Value2.

    You may be wondering what is the difference between Value, Value2 and the default:

    ' Value2
    Range("A1").Value2 = 56
    
    ' Value
    Range("A1").Value = 56
    
    ' Default uses value
    Range("A1") = 56
    

     
    Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.

    It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)

    The Range Property

    The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.

    The following example shows you how to place a value in a cell using the Range property.

    ' https://excelmacromastery.com/
    Public Sub WriteToCell()
    
        ' Write number to cell A1 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67
    
        ' Write text to cell A2 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith"
    
        ' Write date to cell A3 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017#
    
    End Sub
    

     
    As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.

    For the rest of this post I will use the code name to reference the worksheet.

    code name worksheet

     
     
    The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).

    ' https://excelmacromastery.com/
    Public Sub UsingCodeName()
    
        ' Write number to cell A1 in sheet1 of this workbook
        Sheet1.Range("A1").Value2 = 67
    
        ' Write text to cell A2 in sheet1 of this workbook
        Sheet1.Range("A2").Value2 = "John Smith"
    
        ' Write date to cell A3 in sheet1 of this workbook
        Sheet1.Range("A3").Value2 = #11/21/2017#
    
    End Sub
    

    You can also write to multiple cells using the Range property

    ' https://excelmacromastery.com/
    Public Sub WriteToMulti()
    
        ' Write number to a range of cells
        Sheet1.Range("A1:A10").Value2 = 67
    
        ' Write text to multiple ranges of cells
        Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith"
    
    End Sub
    

     
    You can download working examples of all the code from this post from the top of this article.
     

    The Cells Property of the Worksheet

    The worksheet object has another property called Cells which is very similar to range. There are two differences

    1. Cells returns a range of one cell only.
    2. Cells takes row and column as arguments.

     
    The example below shows you how to write values to cells using both the Range and Cells property

    ' https://excelmacromastery.com/
    Public Sub UsingCells()
    
        ' Write to A1
        Sheet1.Range("A1").Value2 = 10
        Sheet1.Cells(1, 1).Value2  = 10
    
        ' Write to A10
        Sheet1.Range("A10").Value2 = 10
        Sheet1.Cells(10, 1).Value2  = 10
    
        ' Write to E1
        Sheet1.Range("E1").Value2 = 10
        Sheet1.Cells(1, 5).Value2  = 10
    
    End Sub
    

     
    You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.

    For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.

    Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.

     
    In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.

    ' https://excelmacromastery.com/
    Public Sub WriteToColumn()
    
        Dim UserCol As Integer
        
        ' Get the column number from the user
        UserCol = Application.InputBox(" Please enter the column...", Type:=1)
        
        ' Write text to user selected column
        Sheet1.Cells(1, UserCol).Value2 = "John Smith"
    
    End Sub
    

     
    In the above example, we are using a number for the column rather than a letter.

    To use Range here would require us to convert these values to the letter/number  cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.

    Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.

    Using Cells and Range together

    As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows

    ' https://excelmacromastery.com/
    Public Sub UsingCellsWithRange()
    
        With Sheet1
            ' Write 5 to Range A1:A10 using Cells property
            .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
    
            ' Format Range B1:Z1 to be bold
            .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
    
        End With
    
    End Sub
    

     
    As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.

     
    In the following example we print out the address of the ranges we are using:

    ' https://excelmacromastery.com/
    Public Sub ShowRangeAddress()
    
        ' Note: Using underscore allows you to split up lines of code
        With Sheet1
    
            ' Write 5 to Range A1:A10 using Cells property
            .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
            Debug.Print "First address is : " _
                + .Range(.Cells(1, 1), .Cells(10, 1)).Address
    
            ' Format Range B1:Z1 to be bold
            .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
            Debug.Print "Second address is : " _
                + .Range(.Cells(1, 2), .Cells(1, 26)).Address
    
        End With
    
    End Sub
    

     
    In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)

     
    ImmediateWindow

     
    ImmediateSampeText

     
    You can download all the code for this post from the top of this article.
     

    The Offset Property of Range

    Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.

     
    VBA Offset

     
    We will first attempt to do this without using Offset.

    ' https://excelmacromastery.com/
    ' This sub tests with different values
    Public Sub TestSelect()
    
        ' Monday
        SetValueSelect 1, 111.21
        ' Wednesday
        SetValueSelect 3, 456.99
        ' Friday
        SetValueSelect 5, 432.25
        ' Sunday
        SetValueSelect 7, 710.17
    
    End Sub
    
    ' Writes the value to a column based on the day
    Public Sub SetValueSelect(lDay As Long, lValue As Currency)
    
        Select Case lDay
            Case 1: Sheet1.Range("H3").Value2 = lValue
            Case 2: Sheet1.Range("I3").Value2 = lValue
            Case 3: Sheet1.Range("J3").Value2 = lValue
            Case 4: Sheet1.Range("K3").Value2 = lValue
            Case 5: Sheet1.Range("L3").Value2 = lValue
            Case 6: Sheet1.Range("M3").Value2 = lValue
            Case 7: Sheet1.Range("N3").Value2 = lValue
        End Select
    
    End Sub
    

     
    As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution

    ' https://excelmacromastery.com/
    ' This sub tests with different values
    Public Sub TestOffset()
    
        DayOffSet 1, 111.01
        DayOffSet 3, 456.99
        DayOffSet 5, 432.25
        DayOffSet 7, 710.17
    
    End Sub
    
    Public Sub DayOffSet(lDay As Long, lValue As Currency)
    
        ' We use the day value with offset specify the correct column
        Sheet1.Range("G3").Offset(, lDay).Value2 = lValue
    
    End Sub
    

     
    As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.

     
    One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset

    ' https://excelmacromastery.com/
    Public Sub UsingOffset()
    
        ' Write to B2 - no offset
        Sheet1.Range("B2").Offset().Value2 = "Cell B2"
    
        ' Write to C2 - 1 column to the right
        Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2"
    
        ' Write to B3 - 1 row down
        Sheet1.Range("B2").Offset(1).Value2 = "Cell B3"
    
        ' Write to C3 - 1 column right and 1 row down
        Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3"
    
        ' Write to A1 - 1 column left and 1 row up
        Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1"
    
        ' Write to range E3:G13 - 1 column right and 1 row down
        Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13"
    
    End Sub
    

    Using the Range CurrentRegion

    CurrentRegion returns a range of all the adjacent cells to the given range.

    In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.

    VBA CurrentRegion

    A row or column of blank cells signifies the end of a current region.

    You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.

    If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.

    For example
    Range(“B3”).CurrentRegion will return the range B3:D14
    Range(“D14”).CurrentRegion will return the range B3:D14
    Range(“C8:C9”).CurrentRegion will return the range B3:D14
    and so on

    How to Use

    We get the CurrentRegion as follows

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    

    Read Data Rows Only

    Read through the range from the second row i.e.skipping the header row

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    
    ' Start at row 2 - row after header
    Dim i As Long
    For i = 2 To rg.Rows.Count
        ' current row, column 1 of range
        Debug.Print rg.Cells(i, 1).Value2
    Next i
    

    Remove Header

    Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    
    ' Remove Header
    Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)
    
    ' Start at row 1 as no header row
    Dim i As Long
    For i = 1 To rg.Rows.Count
        ' current row, column 1 of range
        Debug.Print rg.Cells(i, 1).Value2
    Next i
    

     

    Using Rows and Columns as Ranges

    If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access

    ' https://excelmacromastery.com/
    Public Sub UseRowAndColumns()
    
        ' Set the font size of column B to 9
        Sheet1.Columns(2).Font.Size = 9
    
        ' Set the width of columns D to F
        Sheet1.Columns("D:F").ColumnWidth = 4
    
        ' Set the font size of row 5 to 18
        Sheet1.Rows(5).Font.Size = 18
    
    End Sub
    

    Using Range in place of Worksheet

    You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.

     
    The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2

    ' https://excelmacromastery.com/
    Public Sub UseColumnsInRange()
    
        ' This will set B1 and B2 to be bold
        Sheet1.Range("A1:C2").Columns(2).Font.Bold = True
    
    End Sub
    

     
    You can download all the code for this post from the top of this article.
     

    Reading Values from one Cell to another

    In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.

     
    The following example shows you how to do this:

    ' https://excelmacromastery.com/
    Public Sub ReadValues()
    
        ' Place value from B1 in A1
        Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2
    
        ' Place value from B3 in sheet2 to cell A1
        Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2
    
        ' Place value from B1 in cells A1 to A5
        Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2
    
        ' You need to use the "Value" property to read multiple cells
        Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2
    
    End Sub
    

     
    As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter

    ' https://excelmacromastery.com/
    Public Sub CopyValues()
    
        ' Store the copy range in a variable
        Dim rgCopy As Range
        Set rgCopy = Sheet1.Range("B1:B5")
    
        ' Use this to copy from more than one cell
        rgCopy.Copy Destination:=Sheet1.Range("A1:A5")
    
        ' You can paste to multiple destinations
        rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")
    
    End Sub
    

     
    The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.

    Using the Range.Resize Method

    When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.

    Using the Resize function allows us to resize a range to a given number of rows and columns.

    For example:
     

    ' https://excelmacromastery.com/
    Sub ResizeExamples()
     
        ' Prints A1
        Debug.Print Sheet1.Range("A1").Address
    
        ' Prints A1:A2
        Debug.Print Sheet1.Range("A1").Resize(2, 1).Address
    
        ' Prints A1:A5
        Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
        
        ' Prints A1:D1
        Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
        
        ' Prints A1:C3
        Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
        
    End Sub
    

     
    When we want to resize our destination range we can simply use the source range size.

    In other words, we use the row and column count of the source range as the parameters for resizing:

    ' https://excelmacromastery.com/
    Sub Resize()
    
        Dim rgSrc As Range, rgDest As Range
        
        ' Get all the data in the current region
        Set rgSrc = Sheet1.Range("A1").CurrentRegion
    
          ' Get the range destination
        Set rgDest = Sheet2.Range("A1")
        Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
        
        rgDest.Value2 = rgSrc.Value2
    
    End Sub
    

     
    We can do the resize in one line if we prefer:

    ' https://excelmacromastery.com/
    Sub ResizeOneLine()
    
        Dim rgSrc As Range
        
        ' Get all the data in the current region
        Set rgSrc = Sheet1.Range("A1").CurrentRegion
        
        With rgSrc
            Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
        End With
        
    End Sub
    

    Reading Values to variables

    We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.

    ' https://excelmacromastery.com/
    Public Sub UseVariables()
    
        ' Create
        Dim number As Long
    
        ' Read number from cell
        number = Sheet1.Range("A1").Value2
    
        ' Add 1 to value
        number = number + 1
    
        ' Write new value to cell
        Sheet1.Range("A2").Value2 = number
    
    End Sub
    

     
    To read text to a variable you use a variable of type String:

    ' https://excelmacromastery.com/
    Public Sub UseVariableText()
    
        ' Declare a variable of type string
        Dim text As String
    
        ' Read value from cell
        text = Sheet1.Range("A1").Value2
    
        ' Write value to cell
        Sheet1.Range("A2").Value2 = text
    
    End Sub
    

     
    You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.

    ' https://excelmacromastery.com/
    Public Sub VarToMulti()
    
        ' Read value from cell
        Sheet1.Range("A1:B10").Value2 = 66
    
    End Sub
    

     
    You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.

    How to Copy and Paste Cells

    If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.

    Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
    I have written a complete guide to copying data in Excel VBA here.

     
    You can simply copy a range of cells like this:

    Range("A1:B4").Copy Destination:=Range("C5")
    

     
    Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.

     
    It works like this

    Range("A1:B4").Copy
    Range("F3").PasteSpecial Paste:=xlPasteValues
    Range("F3").PasteSpecial Paste:=xlPasteFormats
    Range("F3").PasteSpecial Paste:=xlPasteFormulas
    

     
    The following table shows a full list of all the paste types

    Paste Type
    xlPasteAll
    xlPasteAllExceptBorders
    xlPasteAllMergingConditionalFormats
    xlPasteAllUsingSourceTheme
    xlPasteColumnWidths
    xlPasteComments
    xlPasteFormats
    xlPasteFormulas
    xlPasteFormulasAndNumberFormats
    xlPasteValidation
    xlPasteValues
    xlPasteValuesAndNumberFormats

    Reading a Range of Cells to an Array

    You can also copy values by assigning the value of one range to another.

    Range("A3:Z3").Value2 = Range("A1:Z1").Value2
    

     
    The value of  range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.  

     
    The following code shows an example of using an array with a range:

    ' https://excelmacromastery.com/
    Public Sub ReadToArray()
    
        ' Create dynamic array
        Dim StudentMarks() As Variant
    
        ' Read 26 values into array from the first row
        StudentMarks = Range("A1:Z1").Value2
    
        ' Do something with array here
    
        ' Write the 26 values to the third row
        Range("A3:Z3").Value2 = StudentMarks
    
    End Sub
    

     
    Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns

    Going through all the cells in a Range

    Sometimes you may want to go through each cell one at a time to check value.

     
    You can do this using a For Each loop shown in the following code

    ' https://excelmacromastery.com/
    Public Sub TraversingCells()
    
        ' Go through each cells in the range
        Dim rg As Range
        For Each rg In Sheet1.Range("A1:A10,A20")
            ' Print address of cells that are negative
            If rg.Value < 0 Then
                Debug.Print rg.Address + " is negative."
            End If
        Next
    
    End Sub
    
    

     
    You can also go through consecutive Cells using the Cells property and a standard For loop.

     
    The standard loop is more flexible about the order you use but it is slower than a For Each loop.

    ' https://excelmacromastery.com/
    Public Sub TraverseCells()
     
        ' Go through cells from A1 to A10
        Dim i As Long
        For i = 1 To 10
            ' Print address of cells that are negative
            If Range("A" & i).Value < 0 Then
                Debug.Print Range("A" & i).Address + " is negative."
            End If
        Next
     
        ' Go through cells in reverse i.e. from A10 to A1
        For i = 10 To 1 Step -1
            ' Print address of cells that are negative
            If Range("A" & i) < 0 Then
                Debug.Print Range("A" & i).Address + " is negative."
            End If
        Next
     
    End Sub
    

    Formatting Cells

    Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells

    ' https://excelmacromastery.com/
    Public Sub FormattingCells()
    
        With Sheet1
    
            ' Format the font
            .Range("A1").Font.Bold = True
            .Range("A1").Font.Underline = True
            .Range("A1").Font.Color = rgbNavy
    
            ' Set the number format to 2 decimal places
            .Range("B2").NumberFormat = "0.00"
            ' Set the number format to a date
            .Range("C2").NumberFormat = "dd/mm/yyyy"
            ' Set the number format to general
            .Range("C3").NumberFormat = "General"
            ' Set the number format to text
            .Range("C4").NumberFormat = "Text"
    
            ' Set the fill color of the cell
            .Range("B3").Interior.Color = rgbSandyBrown
    
            ' Format the borders
            .Range("B4").Borders.LineStyle = xlDash
            .Range("B4").Borders.Color = rgbBlueViolet
    
        End With
    
    End Sub
    

    Main Points

    The following is a summary of the main points

    1. Range returns a range of cells
    2. Cells returns one cells only
    3. You can read from one cell to another
    4. You can read from a range of cells to another range of cells.
    5. You can read values from cells to variables and vice versa.
    6. You can read values from ranges to arrays and vice versa
    7. You can use a For Each or For loop to run through every cell in a range.
    8. The properties Rows and Columns allow you to access a range of cells of these types

    What’s Next?

    Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

    Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

    (NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

    • #2

    Hi and Welcome to the Board.
    What specific value are you looking for in «C16»
    AND
    You want to copy range «F3» to «F last cell» to the first blank cell in «F» ?

    • #3

    Hi Michael,

    Thanks for the welcome. Basically I have created an invoice sheet (F3:P43) that uses lookups from standard formulas I use based on client, dates, etc, etc to calculate an invoice from other worksheets. What I was doing to keep track of invoices I’ve issued, is to copy and paste the issued invoice values below F43. I’ve ensured that the F column only contains the invoice numbers. So everything below row 43 contains copies of invoices.

    I created a macro button to copy and paste values of F3:P43, starting from F44, to the next blank cell in column F. The invoices are always 40 rows long, and each cell in F contains the invoice number it corresponds to.

    The reason I want to use VBA is to make sure that I don’t copy and paste duplicates unnecessarily.

    • #4

    Ok, now I’m really confused……so what does «cell «C16» have to do with the copy and paste ?

    • #5

    Sorry Michael,

    I’m a bit tired.

    «C16» is the cell/value I want to check/search against «F44:F1000»

    IF — the value of «C16» is found in «F44:F100»

    THEN — don’t copy and paste

    ELSE — copy and paste

    END IF

    I’ve figured out my copy and paste code. What I’m stuck on, is trying to create a code that will search «F44:F1000» for a value in «C16».

    • #6

    Maybe this

    Code:

    Sub CopyPaste()
    Dim lr As Long
    lr = Cells(Rows.Count, "F").End(xlUp).Row
        For Each cell In Range("F3:F43")
            If cell.Value = Range("C16").Value Then
               MsgBox "Invoice number already issued."
               Exit Sub
            End If
        Next cell
            Range("F3:P43").Copy
            Range("F" & lr + 1).PasteSpecial Paste:=xlPasteValues
        End Sub

    • #7

    Thanks Michael,

    That worked great, the only thing I had to change was Line 4, «F3:F43» to «F44:F1000».

    But is there away to replace «F44:F1000» I entered to some thing like «F44: («F» & lr + 1)»?

    • #8

    MAybe

    Code:

    Sub CopyPaste()
    Dim lr As Long
    lr = Cells(Rows.Count, "F").End(xlUp).Row
        For Each cell In Range("F44:F" & lr)
            If cell.Value = Range("C16").Value Then
               MsgBox "Invoice number already issued."
               Exit Sub
            End If
        Next cell
            'Range("F3:F43").Copy ' so should this line change too !!
            Range("F44:F" & lr).copy ' to this ?
            Range("F" & lr + 1).PasteSpecial Paste:=xlPasteValues
        End Sub

    • #9

    Perfect Michael, thanks a lot. It’s way too late on this side of the world, but I apprecciate all the help. Time for some sleep.

    • #10

    OK, glad it worked. Thanks for the feedback

    Понравилась статья? Поделить с друзьями:
  • Excel vba if cell is not a number
  • Excel vba if cell is colored
  • Excel vba if array is not empty
  • Excel vba if any value in range
  • Excel vba if any cell in range