45

I want to check if a range in Excel is empty.

How do I write in VBA code:

If Range("A38":"P38") is empty
3

8 Answers 8

80

Found a solution from the comments I got.

Sub TestIsEmpty()
    If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
        MsgBox "Empty"
    Else
        MsgBox "Not Empty"
    End If
End Sub
2
  • 3
    Attention: "Empty()" isn't a valid procedure Name. @darren-bartrup-cook, my proposed edit doesn't deviate from the original intent of the post and preserve its goals.
    – T.M.
    Sep 4, 2017 at 12:44
  • 2
    If there is a possibility that the range can contain empty string values (constants) or formulas that could return an empty-string value, and cells with empty-string values must be treated as "empty" then use this expression instead: WorksheetFunction.CountBlank(Range("A38:P38")) = Range("A38:P38").Cells.Count (And maybe use a With statement to clean it up.)
    – pstraton
    Jun 9, 2021 at 22:51
9

If you find yourself in a situation where you can’t use CountA then it's much faster to first store your range as an array and loop on the array's data than it is to individually loop on range/cell data.

Function IsRangeEmpty(ByVal rng As Range) As Boolean
    
    ''Returns true if a value is found in parameter range.
    ''Converts parameter range to an array to check it quickly.
    
    'if range has cells in it then
    If Not rng Is Nothing Then
    
        Dim area As Range
        For Each area In rng.Areas 'checks through all sub-ranges within the original range e.g., rng=Range("A1:B5,C6:D9")
            
            'if sub-range has more than one cell then
            If area.Cells.Count > 1 Then
            
                'save range as array
                Dim arr As Variant
                arr = area.value
                
                'loop through array
                Dim arrCell As Variant
                For Each arrCell In arr
                
                    'if cell is not empty then
                    If Len(Trim(arrCell)) > 0 Then
                        IsRangeEmpty = False
                        Exit Function
                    End If
    
                Next arrCell
                
            Else 'unnecessary to loop on a single cell
                
                'if cell is not empty then
                If Len(Trim(area.Value2)) > 0 Then
                    IsRangeEmpty = False
                    Exit Function
                End If
                
            End If
    
        Next area
    End If
    
    IsRangeEmpty = True

End Function

Example of how to use it:

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

If Range("A38:P38") is empty, it would print True in the Immediate Window.

7
  • 1
    To deal with the case when the range is only one cell, you can use "If rng.Cells.Count < 2 Then ..." and only test this cell.
    – LePatay
    Jan 28, 2019 at 14:00
  • @LePatay thanks for the heads up, I hadn't tested with just one cell! Should be fixed now. Aug 12, 2019 at 14:41
  • This is absolutely something that should be a function! Perfect, thanks :) Feb 1, 2021 at 22:14
  • The example in my comment to Kano's post above, is a simpler way to address this issue.
    – pstraton
    Jun 9, 2021 at 22:58
  • 1
    You should also add a check for ` If Not rng Is Nothing Then` Oct 7, 2021 at 17:35
5

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx) . So you must check every cell in range separately:

    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: 

Of course here are more code than in solution with CountA function which count not empty cells, but GoTo can interupt loops if at least one not empty cell is found and do your code faster especially if range is large and you need to detect this case. Also this code for me is easier to understand what it is doing, than with Excel CountA function which is not VBA function.

2
  • 1
    Excel macro code (don't know if compiling is possible) takes a while when you have large number of iterations. Your solution is needed if you have already determined that some cell in the range is not empty and you want to process it, but the check of determining if a range is empty (ie, if your code is even necessary) should be faster and maybe much faster using the accepted answer (CountA). Using a single "native" function to a VB loop that does the same tends to lead to faster running times.
    – Jose_X
    Dec 15, 2016 at 13:05
  • 1
    this doesn't always work. For instance if you have a range that is not a continuous selection after a selection (lets say your range selection skips 1 cell then it skips 5 cells, goes back to 1 cell, etc,,) then this will error out. Dec 23, 2016 at 20:22
4
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

From experience I just learned you could do:

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

Clarification to be provided a bit later (right now I'm working)

3
  • 1
    Thanks for the answer, could you also provide a bit of clarification what the comparison is really doing for future visitors? EDIT: Also a bit tricky to understand how your edit fits in with the original example.
    – Thor
    Mar 24, 2017 at 8:24
  • @Thor when you search for a solution to the problem on Google, you get this page. But this page doesn't answer that problem which is why i answered that problem. I believe people here don't just up-vote things. I can see this already helped a few people. Mar 29, 2017 at 15:09
  • 1
    @Jean-FrançoisCorbett sadly yes, every single hour of my wakeful life... Look, this helps to the one that seeks. I know that when i was trying to figure this out i came across this page, over and over in google search. This was exactly the solution i was looking for, so i tried to help others out and post it. Even if it isn't a 100% direct help, it's 1000% indirect help. May 25, 2017 at 1:49
3
Dim cel As Range, hasNoData As Boolean

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

This will return True if no cells in Selection contains any data. For a specific range, just substitute RANGE(...) for Selection.

2

Another possible solution. Count empty cells and subtract that value from the total number of cells

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
0

This just a slight addition to @TomM's answer/ A simple function to check if your Selection's cells are empty

Public Function CheckIfSelectionIsEmpty() As Boolean
   Dim emptySelection As Boolean:emptySelection=True
   Dim cell As Range
   For Each cell In Selection
       emptySelection = emptySelection And isEmpty(cell)
       If emptySelection = False Then
          Exit For
       End If
   Next
   CheckIfSelectionIsEmpty = emptySelection
End Function
0

This single line works better imho:

Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")

in this case, it evaluates if range E10:E14 is empty.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.