如何将地址的范围引用分成一个维数的元素

时间:2017-04-12 09:19:42

标签: vba excel-vba excel

我有一个存储在其中的变量类型变量单元格地址和范围地址

e.g:

Dim cells_addresses as variant
Cells_addresses="$A$1,$C$3:$F$3,$F$4"

现在我想在VBA中使用拆分函数或任何其他子函数来将这些单元格地址拆分为一维数组,如下所示:

Output_Array="$A$1","$C$3","$D$3","$E$3","$F$3","$F$4"

任何人都知道如何将地址范围划分为数组的各个元素?

3 个答案:

答案 0 :(得分:2)

您可以使用您提供的Range值设置Cells_addresses。之后,循环遍历Range.Areas,并嵌套在每个Area单元格的下方循环中,每个单元格都添加到Output_Array

<强>代码

Option Explicit

Sub SplitRangeAddrrtoArray()

Dim cells_addresses As Variant
Dim UnionRng As Range
Dim RngArea As Range
Dim C As Range
Dim i As Long
Dim Output_Array() As Variant

cells_addresses = "$A$1,$C$3:$F$3,$F$4"
ReDim Output_Array(0 To 1000) ' init array size >> will optimize later

Set UnionRng = Range(cells_addresses) '<-- Set a Range with the cells addresses provided
' loop through range's areas in case there are multiple areas
For Each RngArea In UnionRng.Areas
    For Each C In RngArea ' loop through the area's cells
        Output_Array(i) = C.Address
        i = i + 1
    Next C
Next RngArea
ReDim Preserve Output_Array(0 To i - 1) '<-- resize to actual populated size

End Sub

答案 1 :(得分:1)

这是一种方式:

Function SplitRanges(RangeString As Variant) As Variant
    Dim ranges As Variant, v As Variant
    Dim c As Range
    Dim i As Long, j As Long, n As Long
    ranges = Split(RangeString, ",")
    For i = 0 To UBound(ranges)
        n = n + Range(ranges(i)).Cells.Count
    Next i
    ReDim v(1 To n)
    i = 0
    For j = 0 To UBound(ranges)
        For Each c In Range(ranges(j)).Cells
            i = i + 1
            v(i) = c.Address
        Next c
    Next j
    SplitRanges = v
End Function

测试如下:

Sub test()
    Dim s As String
    s = "$A$1,$C$3:$F$3,$F$4"
    Debug.Print Join(SplitRanges(s), ",")
End Sub

输出:

$A$1,$C$3,$D$3,$E$3,$F$3,$F$4

答案 2 :(得分:0)

或者像这样...

Dim cells_addresses As Variant
Dim OutputArr()
Dim cell As Range
Dim str() As String
Dim i As Long, ii As Long
cells_addresses = "$A$1,$C$3:$F$3,$F$4"
str() = Split(cells_addresses, ",")
For i = 0 To UBound(str)
    For Each cell In Range(str(i))
        ii = ii + 1
        ReDim Preserve OutputArr(1 To ii)
        OutputArr(ii) = cell.Address
    Next cell
Next i
MsgBox Join(OutputArr, ", ")