To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial). In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”Įxamples of Using IF Then Statement in VBA Hence you need to use the End IF statement.
When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines. However, in the second syntax, the true_code part is in the second line. The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement. Now if you’re wondering what’s the difference between the two syntaxes, let me clarify. Note that the Else part of this statement is optional. Example 4 – Extract the Numeric Part from an Alphanumeric Stringīelow is the generic syntax of If Then Else construct in VBA IF condition Then true_code.Example 3 – Hide All the Worksheet Except the Current Worksheet.Example 2 – Highlight Cells with Negative Values.Example 1 – Save and Close All Workbooks Except The Active Workbook.Nested IF Then (Multiple IF Then statements).Examples of Using IF Then Statement in VBA.