Search code examples
vbaexcelloopsexit-code

Loop stops after one condition is met even if there are multiple


The code below will "exit for" after it meets its condition once even if there are more in the range that meet the condition. How do I correct this?

Private Sub cmdAdd_Click()
    On Error GoTo Whoa
    Dim LastRow As Long, i As Long
    LastRow = ActiveSheet.Range(Me.txtTaskCol.Value & Rows.Count).End(xlUp).Row
    'Copy input values to sheet
    For i = 1 To LastRow
        If UCase(CStr(ActiveSheet.Range(Me.txtTaskCol.Value & i).Value)) = UCase(CStr(Me.txtTask.Value)) Then
            ActiveSheet.Range(Me.txtUnitCol.Value & i).Value = Me.txtQuantity.Value
            Exit For
        Else
            If i = LastRow Then MsgBox "Task Not Found!"
        End If
    Next i
    'Clear input controls
    Me.txtTask.Value = ""
    Me.txtQuantity.Value = ""
    Exit Sub

Whoa:
        Select Case Err.Number
            Case 1004
                MsgBox "Check for Valid Column Letters!"
        End Select

End Sub

Solution

  • Just use a boolean flag that will set the flag to True if your If...Then statement is true one time:

    If you are wanting to continue your For...Next statement after you meet the criteria, then you don't want to exit for.

    Private Sub cmdAdd_Click()
        On Error GoTo Whoa
        Dim LastRow As Long, i As Long, tskFlg As Boolean
        LastRow = ActiveSheet.Range(Me.txtTaskCol.Value & Rows.Count).End(xlUp).Row
        'Copy input values to sheet
        For i = 1 To LastRow
            If UCase(CStr(ActiveSheet.Range(Me.txtTaskCol.Value & i).Value)) = UCase(CStr(Me.txtTask.Value)) Then
                ActiveSheet.Range(Me.txtUnitCol.Value & i).Value = Me.txtQuantity.Value
                tskFlg = True
            End If
        Next i
        If tskFlg = False Then MsgBox "Task Not Found!"
        'Clear input controls
        Me.txtTask.Value = ""
        Me.txtQuantity.Value = ""
        Exit Sub
    
    Whoa:
            Select Case Err.Number
                Case 1004
                    MsgBox "Check for Valid Column Letters!"
            End Select
    
    End Sub