aggieman
aggieman

Reputation: 49

vba array element removal

j = LBound(arrayTime)
Do Until j = UBound(arrayTime)
    j = j + 1
    b = b + 1
    cnc = b + r
    MsgBox cnc
        If cnc > 7 Then
            b = 0
            r = 0
            cnc = b + r
        End If
    numMins = Sheet5.Cells(cnc + 3, 2) - arrayTime(j)
    If numMins < 0 Then
        g = g + 1
        ReArrangeArray arrayTime, j
        'ReDim Preserve arrayTime(numrows - 1 + g)
        'arrayTime(numrows - 1 + g) = arrayTime(j)
        'MsgBox (arrayTime(numrows - 1 + g))
    Else
        Sheet5.Cells(cnc + 3, 2) = numMins
    End If
Loop

If the if statement is true I want to be able to put the array value at the end of the array and remove that value from its current spot. As the code is, it just adds it to the end and increases the size of the array from 12 to 13. How can I get the array to remain size 12 and still place the value at the end of the array and then remove it from its original position? I do not want to touch the array values in front. Just want to take that value and move it to the end. For instance array(1,2,3,4,5) If statement j on third loop. array(j)=3 end array should be array(1,2,4,5,3)

Upvotes: 1

Views: 119

Answers (1)

user3598756
user3598756

Reputation: 29421

You could use a helper Sub like this one:

Sub ReArrangeArray(inputArray as Variant, indexToSwap as long)
    Dim I As Long
    Dim tempVal As Variant

    If indexToSwap >= LBound(inputArray) And indexToSwap < UBound(inputArray)  Then
        tempVal = inputArray(indexToSwap)
        For I = indexToSwap To UBound(inputArray) - 1
            inputArray(i) = inputArray(i + 1)
        Next I
        InputArray(UBound(inputArray))  = tempVal 
    End If
End Sub

To be called by your main Sub as follows:

ReArrangeArray arrayTime, j

Upvotes: 1

Related Questions