Search code examples
excelvbauserformmsgbox

VBA - Msgbox inside a Loop


I have the attached userform. Whenever I click on the "Proceed!" button, I have it check if the sum of batches weight is more than the first assigned weight in the Product Details frame;

if yes it asks me to proceed or not, I the answer was "Yes" it continues, If "No" I want it to let me change the quantities again in the userform.

I have written the below code but when I hit "No" the msgbox keeps showing again and again:

Private Sub CommandButton1_Click()     'Proceed! Button
Dim answer As Integer

q = Val(Left(Label2.Caption, 5))       'Weight in Product Details --> 15.12 tons 

Total = BatchTotal1 + BatchTotal2 + BatchTotal3 + BatchTotal4 + BatchTotal5  'Publicly dimmed previously

Again:

If Total > q Then
    answer = MsgBox("Batches total weight is more than you assigned first, Do you want to proceed?", vbQuestion + vbYesNo)
    If answer = vbYes Then
        GoTo Continue
    Else
        GoTo Again
    End If
End If

Continue:

'Another code

Solution

  • Avoid GoTo if at all possible. Try this:

    Private Sub CommandButton1_Click()     'Proceed! Button
    
        Dim answer As Long
    
        q = Val(Left(Label2.Caption, 5))       'Weight in Product Details --> 15.12 tons 
    
        Total = BatchTotal1 + BatchTotal2 + BatchTotal3 + BatchTotal4 + BatchTotal5  'Publicly dimmed previously
        If Total > q Then
            answer = MsgBox("Batches total weight is more than you assigned first, Do you want to proceed?", vbQuestion + vbYesNo)
            If answer <> vbYes Then
                Exit Sub
            Else
        End If
    
        ' Another code
    
    End Sub