我如何修复此代码,从VBA中的另一个数组中删除所有非零元素?

时间:2016-04-18 14:22:35

标签: arrays vba excel-vba debugging excel

我编写了一些代码,可以从一个数组中删除所有非零项。但它有一些错误,我似乎无法解决它。 例如,如果

A(1) = 0 
A(2) = 3
A(3) = 0 
A(4) = 4
for i = 1 to 4
    B(i) = i
next i

我希望B在

之后看起来像这样

B =(1,2)

For i = 1 To UBound(A) - 1
If A(i) <> 0 Then
    count = count + 1 
End If
Next i

For j = 1 To count
k = 1
Do While k < UBound(A)
If A(k) <> 0 Then 'If A is not equal to 0
    A(k) = m
    For i = m To UBound(B) - 1
        B(i) = B(i + 1)
    Next i
    ReDim Preserve B(1 To UBound(B) - 1)
Else
End If
k = k + 1
Loop

2 个答案:

答案 0 :(得分:1)

不需要ReDim Preserve,因为在计算原始数组中非零项目的数量后,您拥有所需的所有信息。这是一个例子:

Option Explicit

Sub test()
    Dim testdata() As Variant
    Dim resultdata() As Variant
    testdata = Array(2, 1, 0, 3, 0, 4, 2, 4, 5, 0, 0, 3, 6, 0, 0, 1)
    RemoveZeros testdata, resultdata
    Debug.Print "Original array len= " & UBound(testdata)
    Debug.Print "Results  array len= " & UBound(resultdata)
End Sub

Function RemoveZeros(ByRef inputArray() As Variant, _
                     ByRef outputArray() As Variant) As Variant
    Dim numNonZeros As Long
    Dim i As Long
    Dim j As Long

    numNonZeros = 0
    For i = LBound(inputArray) To UBound(inputArray)
        If inputArray(i) <> 0 Then
            numNonZeros = numNonZeros + 1
        End If
    Next i
    If numNonZeros > 0 Then
        '--- create the array and load it up
        j = 1
        ReDim outputArray(j To numNonZeros)
        For i = LBound(inputArray) To UBound(inputArray)
            If inputArray(i) <> 0 Then
                outputArray(j) = inputArray(i)
                j = j + 1
            End If
        Next i
    Else
        ReDim outputArray(1 To 1)
        outputArray(1) = 0
    End If
    RemoveZeros = outputArray
End Function

答案 1 :(得分:0)

这能为你完成这项工作吗?

user1: id = 1; name = A;  
user2: id = 2; name = B;  
user3: id = 3; name = C;

chat1: id = 1; name = A;  
chat2: id = 2; name = B;

user_chat1: id = 1; user = user1; chat = chat1;  
user_chat2: id = 2; user = user2; chat = chat1;
user_chat3: id = 3; user = user1; chat = chat2;  
user_chat4: id = 4; user = user2; chat = chat2;  
user_chat5: id = 5; user = user3; chat = chat2;