首页 > 解决方案 > Excel VBA 数组:有没有一种简单的方法可以按索引删除数据集?

问题描述

是否有一种简单的方法可以通过索引从数组中删除特定数据集?

例子:

Dim array() as string

ReDim array(2,2)

array(0,0) = "abc"
array(0,1) = "Peter"
array(0,2) = "New York"

array(1,0) = "xyz"
array(1,1) = "Bob"
array(1,2) = "Los Angeles"

array(2,0) = "klm"                       ' edited (enumeration error in OP)
array(2,1) = "Stacey"
array(2,2) = "Seattle"

所以我的数组显示在
0: abc, Peter,New York
1: xyz, Bob, Los Angeles
2: klm, Stacey, Seattle

我现在从之前的计算中知道我不再需要索引 1的 Bob ,我想删除他的记录

有没有像下面这样简单的东西?

ReDim Preserve array(UBound(array) - 1)
array.delete(1)

标签: arraysexcelvba

解决方案


试试这个一维数组

Sub test()
Dim strr As String
strr = "0|1|2|3|5"
wArr = Split(strr, "|")
d = DeleteElementAt(2, strr)
End Sub


Function DeleteElementAt(ByVal index As Integer, ByRef prLsts, strDelimeter) As String
       Dim i As Integer
        Dim newLst
        ' Move all element back one position
        prLst = Split(prLsts, strDelimeter)
        If UBound(prLst) > 0 Then
            ReDim newLst(UBound(prLst) - 1)
            For i = 0 To UBound(prLst)
                If i <> index Then newLst(y) = prLst(i): y = y + 1
            Next
            DeleteElementAt = Join(newLst, strDelimeter)
        Else
            DeleteElementAt = prLsts
        End If

End Function

对于二维数组

Function Delete2dElementAt(ByVal index As Integer, ByRef prLsts) As Variant
       Dim i As Integer
        Dim newLst
        ' Move all element back one position
        prLst = prLsts
        If index > UBound(prLst) Then MsgBox "overcome index": Exit Function
        If UBound(prLst) > 0 Then
            ReDim newLst(UBound(prLst) - 1, UBound(prLst, 2))
            For i = 0 To UBound(prLst)
                If i <> index Then
                    For Z = LBound(prLst, 2) To UBound(prLst, 2)
                        newLst(y, Z) = prLst(i, Z)
                    Next Z
                    y = y + 1
                End If
            Next
            Delete2dElementAt = newLst
        Else
            Delete2dElementAt = prLsts
        End If

End Function

推荐阅读