Search code examples
excelvbaexcellibrary

How to fix vba code when it seems to not be reading my conditions?


The vba code seems to not be reading my conditions

I tried ="condition" and now with like and none of them seem to work

This is my code. The code is running with no issues but nothing is getting copied where it should (cells &j)

please help help help

Sub formatpkg()

Dim i, lrow, j, nextl As Integer
Dim val, size, recipe As String


lrow = 5231

For i = 1 To lrow
val = Worksheets("PKG").Range("a" & i).Value
j = 1
If val Like "Recipe Slot*" Then
j = j + 1
Worksheets("Results").Range("a" & j).Value = val
ElseIf val Like "Unit Weight*" Then
Worksheets("Results").Range("b" & j).Value = val
ElseIf UCase(Left(val, 2)) Like "GC" Then
Worksheets("Results").Range("C" & j).Value = val
Else
i = i + 1

End If

Next

End Sub

Solution

  • Your assumption about reading conditions is incorrect. Using debug.print, breaks, msgbox, watch window, etc. will show that the conditions are being read correctly.

    One problem is that you have j = 1 inside your loop, so you keep resetting the value every time you go through the loop. Move it outside the loop, or get rid of it.

    Another problem is that you have i = i + 1 inside your loop. You don't use this statement in this kind of loop. Each time your loop hits the Next statement, it moves to the next value of i.

    Best practice is to use spacing and indentation in code, exactly because it helps make this kind of mistake easier to see. Making code easier to read is much more important than saving a few letters or lines.

    Have made some other corrections to your declarations and example of how to test your theory about conditions.

    Sub formatpkg()
    
    Dim i As Long, lrow As Long, j As Long, nextl As Long
    Dim val As String, size As String, recipe As String
    
    lrow = 5231
    j = 1   'Or j = 0, or delete this line
    
    For i = 1 To lrow
        
        val = Worksheets("PKG").Range("a" & i).Value
            
        If val Like "Recipe Slot*" Then
            Debug.Print "Row " & i, val, "matches Recipe Slot" 'example of how to use debug.print to check your code
            j = j + 1
            Worksheets("Results").Range("a" & j).Value = val
        ElseIf val Like "Unit Weight*" Then
            Worksheets("Results").Range("b" & j).Value = val
        ElseIf UCase(Left(val, 2)) Like "GC" Then
            Worksheets("Results").Range("C" & j).Value = val
        Else
            Debug.Print "Row " & i, val, "no match" 'example of how to use debug.print to check your code
        End If
    
    Next
    
    End Sub