VBA101: A practical guide for VBA user

This post discusses how to write VBA Conditional Statements and how to write VBA Loops

How to write VBA Conditional Statements

If … Else If … Else

If a = b Then
‘ do something
Else If c <> d Then
‘ do another thing
End If

Select Case

Select Case x
Case Is 1
y = 1
Case Is 2
y = 2
Case Else
y = 0
End Select

How to write Various VBA Loops

Do … Loop Until …

Do
‘ do something
Loop Until x < y

Do While … Loop

Do While x < y
‘ do something
Loop

Do While Not … Loop

Do While Not x < y
‘ do something
Loop

For … Next Loop

Dim i As Integer
For i = 1 To 5
‘ do something
Next i

For … Next Loop with Step

Dim i As Integer
For i = 10 to 1 Step -1
‘ do something
Next i

For Each … in … Next Loop

For Each x in xList
‘ do something
Next x

Loop and GoTo (NOT RECOMMENDED)

Dim j As Integer
For i = 0 To 5
b:
If (j = 3) Then GoTo a:
j = i
Next i
a:
j = 4
GoTo b:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: