2

I created an array with named ranges in it.

enter image description here

Here's my code:

Sub Macro()
    ' - - - - - - - - - - - - - - - - -
    Dim fruits As Variant
    fruits = Array("Apple", "Banana", "Coconut")

    For i = 1 To Length(fruits)

     Cells(5, i).Select
        ActiveCell.FormulaR1C1 = Range(fruits.Cells(i))(1)

    Next i
    End Sub

I'd like to call these named ranges from an array in a for loop. How can I do that? Thank you in advance.

I'd like to display the values of the named ranges, let's say, in the 5th row.

2 Answers 2

1

1-D arrays are zero-based by default, not one-based.

Sub Macro()
    Dim fruits As Variant

    fruits = Array("Apple", "Banana", "Coconut")

    For i = lbound(fruits) to ubound(fruits)
        Cells(5, i + 1) = Range(fruits(i))(1)
        'maybe this
        'Cells(5, i + 1) = Range(fruits(i)).cells(1, 2)
    Next i
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

You're super, @Jeeped! Thank you :)
1

Array can be parsed to a range with one line:

Sub TestMe()

    Dim fruits As Variant
    Cells.Clear
    fruits = Array("Apple", "Banana", "Coconut")

    Range("A1:C1").Value2 = fruits
    Range("A5:A7").Value2 = Application.Transpose(fruits)

End Sub

enter image description here


Or even "fancier", with non hard-coded ranges:

Sub TestMe()

    Dim fruits As Variant
    Cells.Clear
    fruits = Array("Apple", "Banana", "Coconut")

    Dim fc As Range
    Set fc = Range("E5")

    Range(fc, fc.Offset(ColumnOffset:=UBound(fruits))) = fruits
    Range(fc, fc.Offset(UBound(fruits))) = Application.Transpose(fruits)

End Sub

enter image description here

1 Comment

@Zac - w/o fancy stuff there is no fun.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.