Search code examples
excelvbarowvariable-assignmentnamed-ranges

Assign a Row of a named area to a ranged variable


I want to assign a area of a worksheet to a name and then assign each row of that named area to a ranged variable in VBA.

I am able to assign the named area to a ranged variable but only if I pass the whole area. If I try using .Rows() to save only a specific Row to a ranged variable, Im unable to access any values that should be in the named variable.

Example:


Dim FirstRow as range: set FirstRow = Worksheets("worksheetname").Range("NamedArea").Rows(1)

'Trying to get out any value:
Debug.Print FirstRow 'Runtime Error 13: types incompatible
Debug.Print FirstRow(1) 'Runtime Error 13: types incompatible
Debug.Print FirstRow(1,1) 'Runtime Error 13: types incompatible

'Trying to iterate through values:
For each i in FirstRow
   Debug.Print "hello" ' Output: "hello" 'only once
   Debug.Print "i" 'Runtime Error
next i



Solution

  • a simple example with named range

    'the code must be in the sheets module
    
    Private Sub example()
       Dim i As Range, FirstRow As Range, cc As Long
       
       Set FirstRow = Me.Range("NamedArea").Rows(1)
       
       Debug.Print FirstRow.Address
       Debug.Print FirstRow.Cells(1, 1)
    
       For Each i In FirstRow.Cells
          cc = cc + 1
          Debug.Print cc & ". " & i.Address & " = " & i.Value
       Next i
       
    End Sub
    
    
    'if you want to set this sub in a module out of any sheet's module, 'the better is to call it with two parameters:
    
    Public Sub example(ws As Worksheet, rngName As String)
       Dim i As Range, FirstRow As Range, cc As Long
       
       Set FirstRow = ws.Range(rngName).Rows(1)
       
       Debug.Print FirstRow.Address
       Debug.Print FirstRow.Cells(1, 1)
    
       For Each i In FirstRow.Cells
          cc = cc + 1
          Debug.Print cc & ". " & i.Address & " = " & i.Value
       Next i
       
    End Sub
    
    
    'and from a sheet's module call it like this:
    
    Private Sub callExample()
       Call example(Me, "NameOfAnyNamedRange")
    End Sub