Programming Structures

1. If, Then Statements

If-then statements allow you to perform different sets of actions if certain conditions are met or are not met.

If condition1 Then
Actions1
ElseIf condition2 Then
Actions2
Else
Actions3
End If

For a single action you can put everything in a single line:

If condition Then action

2. Select, Case

The Select-Case statement is used to list possible situations in which certain actions should be performed. This is conceptually the same as an if/else statement, but easier to read.

Select Case UserValue
Case 1
Actions1
Case 2
Actions2
Case Else
ActionsElse
End Select

You can also use the expresions To, Is =, <>, <, <=, > o >=

Case 1 To 10
Case Is <=10

3. For, next

The structure of For, Next loops is as follows:

For i = 1 To 10
Actions
Next i

For i = 1 To 10 Step 2
Actions
Next i

For i = 10 To 1 Step -1
Actions
Next i

4. Do Loops

Do Loops perform a set of actions repeatedly while or until a condition is met.

Do While count < 10
actions
count = count + 1
Loop

Do Until count > 10
actions
count = count + 1
Loop

You can also check the condition after performing the actions

Do
actions
count = count + 1
Loop While count < 10

Do
actions
count = count + 1
Loop Until count > 10

Exiting Loops

To exit a loop we use Exit For and Exit Do depending on the loop. The command will stop executing the loop and move to the next line of code after the Next/Loop statement.

 5. The With Construct

The With construct is used to set several properties or use several methods of one object in an enclosed statement.

With Range(“A1:B5”)
.Interior.Color = vbRed
.Font.Bold = True
.Font.Name = “Arial”
.Borders(xlEdgeBottom).LineStyle = xlDash
End With

 6. For, each, next

For Each, Next loops use objects as the loop counter.

For Each ws In ActiveWorkbook.Worksheets
actions
Next ws

For Each r in Worksheets(“Sheet1”).Range(“A1:D10”).Cells
For Each nm In ActiveWorkbook.Names

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.