iskbaloch
iskbaloch

Reputation: 197

How to repeat CommandButton1 execution until the condition is met?

I have a Excel VBA code executed by CommandButton1_Click. Following are conditions I have inserted at the end of my VBA code.

If Range("D1").Value < 362 Then
    Range("C1").Value = Range("C1").Value + 7
    Range("D1").Value = Range("D1").Value + 7   
Else
    Range("C1").Value = Range("F2").Value
    Range("D1").Value = 0    
End If

I want to repeat CommandButton1_Click action until Range("D1").Value is turned to Zero again. Please help.

Upvotes: 1

Views: 134

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37500

I think you would need wrap your entire body of CommandButton1_Click method in a Do While ... Loop.

So transform:

Sub CommandButton1_Click()
    'body
End Sub

to

Sub CommandButton1_Click()
    Do While Range("D1").Value <> 0
        'body
    Loop
End Sub

Or you could be more elegant:

Sub SomeSub()
    'your CommandButton1_Click current body
End Sub

Sub CommandButton1_Click()
    Do While Range("D1").Value <> 0
        SomeSub
    Loop
End Sub

Upvotes: 2

DisplayName
DisplayName

Reputation: 13386

as per your own words

Do Until Range("D1").Value = 0
    If Range("D1").Value < 362 Then

        Range("C1").Value = Range("C1").Value + 7
        Range("D1").Value = Range("D1").Value + 7

    Else
        Range("C1").Value = Range("F2").Value
        Range("D1").Value = 0        
    End If
Loop

Upvotes: 1

Related Questions