Как вызвать именованные диапазоны из массива в цикле for в Excel VBA? - PullRequest
0 голосов
/ 03 мая 2018

Я создал массив с именованными диапазонами.

enter image description here

Вот мой код:

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

Я бы хотел назвать эти именованные диапазоны из массива цикла for. Как я могу это сделать? Заранее спасибо.

Я бы хотел отобразить значения именованных диапазонов, скажем, в 5-й строке.

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Массив может быть проанализирован в диапазоне одной строкой:

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


Или даже "любитель", с не жестко заданными диапазонами:

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

0 голосов
/ 03 мая 2018

1-D массивы по умолчанию начинаются с нуля, а не с единицы.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...