Pretty new to VBA, I can't figure out what i'm missing. I'm sure there is an easier way but i'm looking to understand why my code doesn't work. Please correct my code and if you feel inclined, show me a better method.
Goal: Examine the values in Col 3 for all rows, if a match is found, determine which value is bigger in Col 5 between the two rows and delete the row with the smaller value.
Problem: Once a duplicate is found and a row is deleted, the values of the cells are no longer returned. I'm using a MsgBox to show the values and no data is shown.
Goal: Examine the values in Col 3 for all rows, if a match is found, determine which value is bigger in Col 5 between the two rows and delete the row with the smaller value.
Problem: Once a duplicate is found and a row is deleted, the values of the cells are no longer returned. I'm using a MsgBox to show the values and no data is shown.
VBA Code:
Sub Multi()
Dim i As Integer
Dim x As Integer
Dim uVal As Integer
Dim tNUM() As Variant
Dim r As Range
Set r = Range("A:A")
'Count cells in column A to determine how many rows we are working with.
uVal = WorksheetFunction.CountA(r)
ReDim tNUM(uVal, 2) As Variant
x = 1
'Enter data from columns 3 & 5 into array
Do While IsEmpty(Sheet4.Cells(x, 2)) = False
tNUM(x, 1) = Sheet4.Cells(x, 3)
tNUM(x, 2) = Sheet4.Cells(x, 5)
x = x + 1
Loop
x = 1
i = 1
'loop through each cell
Do While x < WorksheetFunction.CountA(r)
Start:
Do Until i > UBound(tNUM)
MsgBox "Testing Sval:" & Sheet4.Cells(x, 3).Value & " Aval: " & tNUM(i, 1) ' testing purposes
If Sheet4.Cells(x, 3) <> tNUM(i, 1) Then 'if cell doesn't match corresponding value in array position, move to next
i = i + 1
ElseIf Sheet4.Cells(x, 3) = tNUM(i, 1) And Sheet4.Cells(x, 5) <> tNUM(i, 2) Then 'if cell matches corresponding value in array position, check that column 5 doesn't match too, delete the row with a smaller value in column 5
MsgBox "Found Duplicate WO# " & Sheet4.Cells(x, 3)
If Sheet4.Cells(x, 5) > tNUM(i, 2) Then
Sheet4.Rows(i).Delete
tNUM = FixArray(tNUM(), i) ' remove the values in array that correspond with the row that was deleted so array data matches left over row values
i = 1
GoTo Start 'go back to the begining of the loop so x is not incremented, if I delete row 2, row 3 now becomes row 2
ElseIf Sheet4.Cells(x, 5) < tNUM(i, 2) Then
Sheet4.Rows(x).Delete
tNUM = FixArray(tNUM(), x) '' remove the values in array that correspond with the row that was deleted so array data matches left over row values
i = 1
GoTo Start
End If
Else
i = i + 1
End If
Loop
i = 1
x = x + 1
Loop
End Sub