If-then-else statements exist in VBA
You can create if-then statements in Excel VBA macros
Perhaps you’re one of the people who appreciates the power of If functions as one of the most essential of Excel functions. Assuming that’s true, it’s going to kind of feel like coming home when you realise that you get the same thing with if-then statements in Excel VBA. Lovely.
Comparison with Excel's If function
- Downloaded this example standard Excel If function spreadsheet
- Clicked on cell B6
- Clicked on Excel’s insert function (“fx”) button on the taskbar.
This is what pops up:
Notice the structure for the standard If function:
- First there’s a logical test
- If the logical test is true then we proceed with whatever we’ve got in the first box
- If the logical test is anything else but true, then we proceed with whatever we’ve got in the second box.
Notice the if-then-else structure. That’s what we get working in Excel VBA. You’ll see that working shortly because we’ve got an example coming up for you.
You also get And, Or, Not in VBA
And Or statements in Excel VBA macros
Maybe you’ve played with Excel’s And/ Or functions. It might be comforting to know that you get those ones in VBA as well!
For the same money (think of it as a bonus, but maybe it isn’t the best you’ve ever had) you also get something called “Not” in VBA. We’re yet to use that one in Excel financial modelling but never mind – it exists.
Coming up next: an example where we can see all of this happening together
To summarise what we’re learning about variables so far:
- You can perform basic operations on variables
- You can use the Excel functions you are used to in VBA (in VBA they are called “Worksheet functions”)
- You can manipulate variables using the familiar if, then, else logic
- Plus you get to do a few other things to variables with And, Or, Not.
Perhaps it would help to look at an example where you can see some of this happening. That’s what we’ve got coming up in the next lesson, at the same time as we look at the usefulness of the “GoTo” statement in controlling program flow.
About this online financial modelling course material
You’re looking at a free online financial modelling course extract covering macros.