Deleting Elements in an Array if Element is a Certain value VBA

后端 未结 8 1425
小蘑菇
小蘑菇 2020-11-27 20:14

I have a global array, prLst() that can of variable length. It takes in numbers as strings \"1\" to Ubound(prLst). However, when the

8条回答
  •  一生所求
    2020-11-27 20:45

    here is a sample of code using the CopyMemory function to do the job.

    It is supposedly "much faster" (depending of the size and type of the array...).

    i am not the author, but i tested it :

    Sub RemoveArrayElement_Str(ByRef AryVar() As String, ByVal RemoveWhich As Long) 
    
    '// The size of the array elements
    '// In the case of string arrays, they are
    '// simply 32 bit pointers to BSTR's.
    Dim byteLen As Byte
    
    '// String pointers are 4 bytes
    byteLen = 4
    
    '// The copymemory operation is not necessary unless
    '// we are working with an array element that is not
    '// at the end of the array
    If RemoveWhich < UBound(AryVar) Then
        '// Copy the block of string pointers starting at
        ' the position after the
        '// removed item back one spot.
        CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
            VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
            (UBound(AryVar) - RemoveWhich)
    End If
    
    '// If we are removing the last array element
    '// just deinitialize the array
    '// otherwise chop the array down by one.
    If UBound(AryVar) = LBound(AryVar) Then
        Erase AryVar
    Else
        ReDim Preserve AryVar(LBound(AryVar) To UBound(AryVar) - 1)
    End If
    End Sub
    

提交回复
热议问题