拆分范围包含多个范围到范围数组?

时间:2015-12-22 12:36:08

标签: arrays excel vba excel-vba range

我试图将多个范围选择转换为范围数组。

现在我正在尝试这个:

Private Function SplitRange(ByRef r As Range) As Range()
    Dim i As Long
    Dim RangesArray() As Range
    Dim AddressArray() As String
    Dim Address As Variant
    i = 0
    AddressArray = Split(r.Address, ",")
    ReDim RangesArray(UBound(AddressArray))
    For Each Address In AddressArray
        Set RangesArray(i) = Range(Address)
        i = i + 1
    Next Address
    ' It works till this point, executing RangesArray(0).Address returns a range address
    SplitRange = RangesArray
    ' Here for some reason neither SplitRange(0).Address or RangesArray(0).Address work
End Function

如何转换"化合物"范围变成一系列范围?

1 个答案:

答案 0 :(得分:2)

Range类型的每个对象都具有属性Areas,其中包含其子范围的集合。您可以对此集合中的项目进行操作,而不是创建数组。

但是如果你真的需要一个数组,你可以轻松地将它转换成:

Public Function SplitRange(ByRef r As Range) As Range()
    Dim i As Long
    Dim ranges() As Range
    Dim subrange As Range
    '----------------------------------------------------------------

    ReDim ranges(0 To r.Areas.Count - 1)
    For Each subrange In r.Areas
        Set ranges(i) = subrange
        i = i + 1
    Next subrange

    SplitRange = ranges

End Function