Badvoc
Badvoc

Reputation: 11

VBA loops to replace multible if statements

I have an Excel worksheet with a repetitive If statement in VBA in a Worksheet_Change sub

If Range("D5") = Range("D4") Then
   Range("c5") = DateAdd("w", Range("i4"), Range("c4"))
Else
   Range("c5") = Range(c2")
End If    
If Range("D6") = Range("D5") Then
   Range("c6") = DateAdd("w", Range("i5"), Range("c5"))
Else
   Range("c6") = Range(c2")
End If

it will repeat from D5 to D150 my question is can I rewrite this in a loop instead of repeating the if statement 145 times?

Im not to good when it comes to loops

Thanks

Upvotes: 0

Views: 87

Answers (1)

riskypenguin
riskypenguin

Reputation: 2199

Try this For loop:

For i = 5 To 150
    If Range("D" & i) = Range("D" & (i-1)) Then
       Range("C"& i) = DateAdd("w", Range("I" & (i-1)), Range("C" & (i-1)))
    Else
       Range("C" & i) = Range("C2")
    End If
Next i

Upvotes: 4

Related Questions