如何从Excel VBA中的for循环中的数组中调用命名范围?

时间:2018-05-03 08:13:53

标签: excel vba excel-vba

我创建了一个包含命名范围的数组。

enter image description here

这是我的代码:

List<List<List<double>>> result = new List<List<List<double>>>();

foreach (var element in uniqueOrdered)
{
    result.Add(lists.FindAll(x=> x.OrderBy(t=>t).SequenceEqual(element)));
}

我想从for循环中的数组中调用这些命名范围。我怎样才能做到这一点?提前谢谢。

我想在第5行显示命名范围的值。

2 个答案:

答案 0 :(得分:1)

默认情况下,1-D阵列从零开始,而不是从1开始。

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

答案 1 :(得分:1)

可以使用一行解析数组:

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