Guy Louzon
Guy Louzon

Reputation: 1213

VBA for excel, WIth to include a condition

I have a simple Sub routine to format selected cells in a certain way I want to have a condition in the process, so that selected cells that match the condition will receive a certain format, and others, another format

I can do it with a simple loop, but my question is specifically for with

Is there something like:

With Selection
    value > 10 THEN HorizontalAlignment = xlCenter
End With

Upvotes: 0

Views: 41

Answers (1)

romulax14
romulax14

Reputation: 555

You can use conditions inside a With. Just use the regular syntax.
Let's say for example you want to change the value of cell A1 to "my value", and if cell A2 value is > 10, then change the horizontal alignment of cell A1.
This would look like :

With Sheets("nameofasheet").Range("A1")
    .Value = "my Value"
    If Sheets("nameofasheet").Range("A2").Value > 10 Then
        .HorizontalAlignment = xlCenter
    End If
End With

Upvotes: 1

Related Questions