使用INDEX选择数组部分

时间:2016-12-26 13:17:11

标签: arrays vba split

我有一个200x4阵列,我需要从第5行到第50行的子集,我怎么能这样做没有循环

这是我的想法,任何建议?

MYARRAY [5:50,]

这只是在VBA中,excel电子表格中没有使用任何信息

1 个答案:

答案 0 :(得分:1)

在纯VBA中是不可能的(虽然你可以通过Index function得到你想要的一些东西。

你可以做的是编写一个切片函数来抽象所需的循环,这样切片的代码就更清晰了。类似的东西:

'Assumes 1-based arrays

Function Slice(A As Variant, Optional RowRange As String = "", Optional ColRange As String = ""):
    Dim i As Long, j As Long, rmin As Long, rmax As Long, cmin As Long, cmax As Long
    Dim m As Long, n As Long
    Dim S As Variant, Dims As Variant

    If Len(RowRange) > 0 Then
        Dims = Split(RowRange, ":")
        rmin = Dims(0)
        rmax = Dims(1)
    Else
        rmin = 1
        rmax = UBound(A, 1)
    End If

    If Len(ColRange) > 0 Then
        Dims = Split(ColRange, ":")
        cmin = Dims(0)
        cmax = Dims(1)
    Else
        cmin = 1
        cmax = UBound(A, 2)
    End If

    m = rmax - rmin + 1
    n = cmax - cmin + 1

    ReDim S(1 To m, 1 To n)
    For i = 1 To m
        For j = 1 To n
            S(i, j) = A(rmin + i - 1, cmin + j - 1)
        Next j
    Next i

    Slice = S
End Function

部分测试:

Sub test()
    Dim A As Variant
    A = Range("A1:C6").Value 'a 4x6 array

    Range("E1:G3").Value = Slice(A, "2:4")
    Range("E5:F10").Value = Slice(A, , "1:2")
End Sub

输出:

enter image description here

不幸的是,Slice(A, "2:4",)是一个语法错误 - 在VBA函数调用中,你不能用逗号终止参数列表,即使剩下的参数是可选的,因此Slice(A, "2:4") vs的不对称性。Slice(A, , "1:2")