I have a global array, prLst()
that can of variable length. It takes in numbers as strings "1"
to Ubound(prLst)
. However, when the user enters "0"
, I want to delete that element from the list. I have the following code written to perform this:
count2 = 0
eachHdr = 1
totHead = UBound(prLst)
Do
If prLst(eachHdr) = "0" Then
prLst(eachHdr).Delete
count2 = count2 + 1
End If
keepTrack = totHead - count2
'MsgBox "prLst = " & prLst(eachHdr)
eachHdr = eachHdr + 1
Loop Until eachHdr > keepTrack
This does not work. How do I efficiently delete elements in the array prLst
if the element is "0"
?
NOTE: This is part of a larger program, for which the description of can be found here: Sorting Groups of Rows Excel VBA Macro
If you want to remove element i , one option would be to move all elements j > i one position to the left ( a[j - 1] = a[j] for all j , or using Array. Copy ) and then resize the array using ReDim Preserve.
You need to use the “Erase” statement to clear an array in VBA. Add the keyword “Erase” before the name of the array that you want to clear but note that all the values will be reset from the array.
The ReDim statement is used to size or resize a dynamic array that has already been formally declared by using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). Use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options
(A) Write a custom 'delete' function for your array like (untested)
Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
Dim i As Integer
' Move all element back one position
For i = index + 1 To UBound(prLst)
prLst(i - 1) = prLst(i)
Next
' Shrink the array by one, removing the last one
ReDim Preserve prLst(Len(prLst) - 1)
End Sub
(B) Simply set a 'dummy' value as the value instead of actually deleting the element
If prLst(eachHdr) = "0" Then
prLst(eachHdr) = "n/a"
End If
(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from
Dim prLst As New Collection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With