0

I have a code that builds up and selects the range to copy it over to another worksheet in another sub.

Sub SelectREZ()

'Disable screen update

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

'Declare variables

    Dim c As Range, ws As Worksheet
    Dim rngG As Range, lastJ, rngJ As Range
    
    Set ws = ActiveSheet

    For Each c In Intersect(ws.UsedRange, ws.Columns("C"))
        Set rngJ = c.EntireRow.Columns("J")
        If c = "REZ" Then
            AddRange rngG, c.EntireRow
            
'Remember the "ITEM NO."
            
            lastJ = rngJ.Value
        Else

            If Len(lastJ) > 0 Then
                If rngJ.Value Like lastJ & "*" Then
                    AddRange rngG, c.EntireRow
                Else
                    lastJ = ""
                End If
            End If
        End If
    Next c
    
    rngG.Select
    
End Sub

'Utility sub for building up a range

    Sub AddRange(rngTot As Range, rngAdd As Range)
    If rngTot Is Nothing Then
        Set rngTot = rngAdd
    Else
        Set rngTot = Application.Union(rngTot, rngAdd)
    End If

'Disable screen update

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub

And I've ran into a situation when the range is empty and macro dies on the line

    rngG.Select

How do I prevent such macro crash and quit the sub if range to select is empty?

I mean I could do:

    On Error Resume Next
    rngG.Select

But it seems like a sledgehammer way to approach it.

braX
  • 11,506
  • 5
  • 20
  • 33
Eduards
  • 68
  • 2
  • 20
  • 4
    `If rngG Is Nothing Then` or `If Not rngG Is Nothing Then` - depending on what happens next. – braX Apr 19 '21 at 08:41
  • 2
    Note that you don't need `select` - and you should avoid it. https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba – FunThomas Apr 19 '21 at 08:45

0 Answers0