MrExcel Publishing
Your One Stop for Excel Tips & Solutions

If statements added to macros

Posted by Bob Wesson on December 15, 2001 5:56 PM

Could someone please show me how to add an If statement to a macro. Say I was recording a macro and wanted to add something like "if this cell doesn't equal (whatever) do this, if it does equan (whatever) do this, then I would like to go back to recording? This task was easy in Quattro Pro. Can't figure it out in excel. PLEASE HELP........


Posted by Jacob on December 15, 2001 6:09 PM

Try this

sub iffy()

If range("a1").value = "whatever" then
do this

do that

end if

end sub

hope this gets you started


Posted by Tom Urtis on December 15, 2001 6:15 PM

It sounds like you are asking about an If Then conditional construct.

Let's say you want to run a part of your code depending on whether or not the value in cell A1 is 5. You can modify the simplified example below to suit your own situation.

Sub IfExample()
If Range("A1").Value = 5 Then
MsgBox ("Hello")
MsgBox ("Goodbye")
End If
End Sub

The Else portion is optional; you can include it to execute code if the If condition you are testing for is not True.

There are other conditional constructs, such as Select Case and Loops, but this If Then Else construct example should get you headed in the right direction.

Tom Urtis