2602
2602

Reputation: 332

VBA: If then with 2 statements after then

How can I write an if then statement where if something is true then 2 actions will be completed? For example:

Sub button()

If Range("B17").Value = 1 Then
Range("C3:F3") = Range("C21:F21").Value And 
Range("C10:F10") = Range("C22:F22").Value

Else

...

End If 

End Sub

Upvotes: 0

Views: 1513

Answers (2)

Error 1004
Error 1004

Reputation: 8230

Try:

Option Explicit

Sub button()

    'First declare your workbook & worksheet
    With ThisWorkbook.Worksheets("Sheet1")
        If .Range("B17").Value = 1 Then
            .Range("C3:F3").Value = .Range("C21:F21").Value
            .Range("C10:F10").Value = .Range("C22:F22").Value
        Else

        End If

    End With

End Sub

Upvotes: 2

John Coleman
John Coleman

Reputation: 52008

In VBA And is a logical connective in which A And B evaluates to True if and only if A and B are both True. It isn't a form of punctuation in which says "do A and then do B". You can just drop the And:

If Range("B17").Value = 1 Then
    Range("C3:F3") = Range("C21:F21").Value
    Range("C10:F10") = Range("C22:F22").Value
Else

    ...

End If 

is unproblematic.

Also, note that the Else clause is optional in VBA. If all you want is for two actions to take place if some condition is true and you don't have alternative actions for when it is false, you can just skip the Else part entirely.

Upvotes: 5

Related Questions