如何删除VB数组中的项目?

时间:2019-06-04 04:41:04

标签: excel vba

在此之后,我要在TargetkyeArr()中删除源密钥'566'     在阵列列表中找到sourcekeys

TargetKeys = "566, 777, 888, 999, 1000"
Dim Arr() As String
TargetkeyArr() = Split(Targetkeys, ",")

Sourcekeys = 566
m = 0
Do While m <= (UBound(TargetKeyArr) - LBound(TargetkeyArr))
  If sourcekeys = Arr(m) Then
         MsgBox "Record found"
         Exit Do
   End If
m = m + 1
Loop

4 个答案:

答案 0 :(得分:0)

这应该有效:

Targetkeys = "566, 777, 888, 999, 1000"

Dim Arr() As String
Dim m As Integer

Arr() = Split(Targetkeys, ",")

sourcekeys = 566

For m = LBound(Arr) To UBound(Arr)

    If sourcekeys = Arr(m) Then

         MsgBox "Record found"

    End If

Next

答案 1 :(得分:0)

遍历元素,并排除以下值:

Function ExcludeAValue(Arr As Variant, Var As Variant) As Variant
    Dim Arr2() As Variant, i As Long
    ReDim Arr2(0 To 0)
    For i = LBound(Arr) To UBound(Arr)
        If Arr(i) <> Var Then
            If Not IsEmpty(Arr2(UBound(Arr2))) Then ReDim Preserve Arr2(0 To UBound(Arr2) + 1)
            Arr2(UBound(Arr2)) = Arr(i)
        End If
    Next
    ExcludeAValue = Arr2
End Function

传递变量时,请确保使用相同的数据类型。

示例:

Sub TestUsingString()
    Dim Targetkeys As String, Excludekey As String, TargetkeyArr As Variant
    Targetkeys = "566, 777, 888, 999, 1000"
    Excludekey = "566"
    TargetkeyArr = ExcludeAValue(Split(Targetkeys, ","), Excludekey)
End Sub
Sub TestUsingLong()
    Dim Targetkeys(0 To 4) As Long, Excludekey As Long, TargetkeyArr As Variant
    Targetkeys(0) = 566
    Targetkeys(1) = 777
    Targetkeys(2) = 888
    Targetkeys(3) = 999
    Targetkeys(4) = 1000
    Excludekey = 566
    TargetkeyArr = ExcludeAValue(Targetkeys, Excludekey)
End Sub
Sub BADTest()
    Dim Targetkeys As String, Excludekey As Long, TargetkeyArr As Variant
    'This one will not exclude it because 566 (long) <> "566" (string)
    Targetkeys = "566, 777, 888, 999, 1000"
    Excludekey = 566
    TargetkeyArr = ExcludeAValue(Split(Targetkeys, ","), Excludekey)
End Sub

答案 2 :(得分:0)

尝试以下代码:

Sub RemoveItem()
    Dim c As Collection
    Set c = New Collection
    Targetkeys = "566, 777, 888, 999, 1000"
    Dim Arr() As String
    sourcekeys = "566"
    For Each Item In Split(Targetkeys, ",")
        ' if item is different, then add it to collection
        If Item <> sourcekeys Then c.Add (Item)
    Next


End Sub

答案 3 :(得分:0)

如果要删除sourceKey值的所有实例,则可以使用Filter

Dim TargetKeyArr As Variant
Dim sourceKeys As Long

TargetKeyArr = Array(566, 777, 888, 999, 1000)

sourceKeys = 566
TargetKeyArr = Filter(TargetKeyArr, sourceKeys, False)

MsgBox Join(TargetKeyArr, ", ")