Excel Vba Introduction 1
Excel Vba Introduction 1
Excel Vba Introduction 1
HARUN KAPLAN
EXCEL VBA:
INTRODUCTION
EXCEL VBA PROGRAMMING -
PART 1
2
Excel VBA: Introduction: Excel VBA programming - Part 1
1st edition
© 2018 Harun Kaplan & bookboon.com
ISBN 978-87-403-2404-4
3
EXCEL VBA: INTRODUCTION Contents
CONTENTS
Introduction 6
2 Developer Environment 9
2.1 VBA-Editor Environment 10
Download now
4
EXCEL VBA: INTRODUCTION Contents
5 Errors in VBA 54
5.1 Errors examples 54
5.2 Handling errors 55
5.3 Toolbar Debug 56
Bibliography 88
5
EXCEL VBA: INTRODUCTION Introduction
INTRODUCTION
This book begins with an introduction to the basics of the editor environment and language
concept of VBA programming. The variety of examples that result from the practice illustrates
the elements of the VBA language to the user with increasing complexity.
The target group of this book is therefore suitable for both beginners and advanced users,
such as users who are up to the advanced user provided.
There are already different books and online guides available. So you ask yourself “What’s
so special about this book?”.
The peculiarity of the book is that it finds its origin in practice and this can be used
excellently as a reference book. The storage locations are not only local places like the hard
disk, but also servers.
In martial arts you learn many ways to fend off an attack. It is important, in an emergency,
not to think about which technique is to be used, but to carry out a defense for each attack.
In VBA there are also plenty of ways to solve a problem, so you have at least one way to
reach your goal.
Harun Kaplan
6
EXCEL VBA: INTRODUCTION Introduction
For my Family:
Tülay
Yasin, Sueda, Melik
7
EXCEL VBA: INTRODUCTION Visual Basic for Application – VBA
Extensive functions and analysis capabilities make working and studying easier because you
get a lot of data and values from different sources to evaluate.
However, with the functions already integrated in Excel you will reach the limits of the Excels.
Operation in Excel is a one-way street. Once you have entered, you either have to stop or
drive to the end of the one-way street. It is very rigid, one process after the other.
With the help of VBA programming, VISUAL BASIC FOR APPLICATIONS, or VBA for
short, Excel becomes more powerful and the user is free and flexible.
It can be used to program both small macros and object-oriented applications or tools.
VBA is a very useful and easy-to-learn programming language. Since VBA is also a (foreign)
language, constant practice is necessary. As you know, practice makes perfect!
The best way to learn programming is to record simple Excel operations. This will familiarize
you with the logic used by VBA syntax.
8
EXCEL VBA: INTRODUCTION Developer Environment
2 DEVELOPER ENVIRONMENT
The developer environment is a parallel world of Excel. It is a stand-alone program, with
its own window system and its own toolbar.
By clicking on “Visual Basic” (Fig.1, 2a) we start with a new macro. For editing existing
macros (Fig. 1, 2b) by clicking on “Macros”.
DDIf the “Developer Tools” menu is not visible, select “File | Excel Options | Developer
Tools “.
The VBA editor is not visible in the development environment the first time you open the
Excel file. This should be done via menu “Insert | Module “.
9
EXCEL VBA: INTRODUCTION Developer Environment
Figure 3: VBA-Surfaces
10
EXCEL VBA: INTRODUCTION Developer Environment
1. VBA-Editor
2. Project Editor
3. Properties
4. Watches
5. Immediate
6. Locals
The most important segment of the VBA environment is the VBA program editor. VBA
provides its own windows for each workbook, for each sheet and for the forms. Here the
program code of the modules is entered. Recorded or manually created program parts can
be called up, adapted or even modified here.
The VBA editor is not visible when you first open an Excel file. We find it in the “Insert
| Module” menu.
The editor writes program sections with individual commands, definitions, and comments
according to VBA syntax rules. If the syntax of the VBA code is correct, the first letters are
converted to uppercase. Otherwise there is a typo.
The operation in this window is similar to a word processor. However, it has a few peculiarities
which are listed below:
11
EXCEL VBA: INTRODUCTION Developer Environment
Figure 4 (bottom left) shows two selection boxes. Depending on which function is selected,
the editor content is shown either one below the other or individually!
In the menu Extras | Options” font color, font size, text input and many other properties
can be set as desired in the VBA editor.
2.1.2 PROJECT-EXPLORER
The presentation of the Project Explorer may be familiar from previous experience with
Windows Explorer. All open VBA projects, such as Excel files with all tables, modules,
diagrams, and Pivot are visible here. These projects can be opened and closed with a plus
or minus sign.
As shown in Figure 5, after opening the Project Explorer, you will see “ThisWorkbook”
and at least one “Table”.
12
EXCEL VBA: INTRODUCTION Developer Environment
Figure 5: Project
The Properties Window displays all of the properties or attributes of an object, such as a
table, a UserForm, or a diagram. These can be customized as needed.
Callable via
These attributes can be changed either directly or in the VBA procedure. This will be
illustrated later in various examples.
The following figure shows two different design representations of a combo box properties window.
13
EXCEL VBA: INTRODUCTION Developer Environment
This window is very useful if testing a macro. There are added terms to monitor here. When
the macro expires, we see what value this expression has.
The monitoring window is called up via the VBA menu command “View | Watch Window “.
14
EXCEL VBA: INTRODUCTION Developer Environment
Download now
15
EXCEL VBA: INTRODUCTION Developer Environment
Or we mark the item to be monitored and drag it with the mouse into the Watch Window,
which is shown in Figure 10.
2.1.6 IMMEDIATE
You can open this window via menu “View | Immediate window” or with the key
combination “Ctrl + g”.
16
• Display determined values of the variables
Sub Immediate_window()
Dim intValue, a, b As Integer
Dim strText As String
a=2
b=5
intValue = a + b
strText = "Microsoft Visual Basic - Excel“
Debug.Print "The Sum of values " & a & " und " & b; " are = " & intValue
Debug.Print "My Text is: " & strText
End Sub
In this window, all variables in the VBA code are monitored simultaneously with the determined
values. When the VBA code is started with F8 "Step to Step", all defined variables are displayed in
the local window with their current values and in defined dimensions.
2.1.7 LOCALS WINDOW
The local window is opened via menu "View | Locals window ".
In this window, all variables in the VBA code are monitored simultaneously with the
determined values. When the VBA code is started with F8 “Step to Step”, all defined variables
are displayed in the local window with their current values and in defined dimensions.
17
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
3 “LEARNING BY RECORDING”
RECORD OF MACRO
The best way to learn VBA programming in Excel is through macro recording.
All Office programs have a macro recorder which allows all actions to be recorded. The
resulting macros are the preliminary stage of VBA programming.
Therefore, it is useful to initially record and optimize many macros in the beginning. That
is why I call this experience “learning by recording”. The more macros we record and then
optimize, the faster we will get into the world of VBA programming and feel “at ease” there.
The recorded macros are used to automate the Excel operation. Recording records all
consecutive actions. The recording is rigid and runs exactly as it was also recorded.
A recorded macro is indeed a very useful tool, unfortunately only with limited automation
of processes. Therefore, we quickly reach the limits of macro recording.
The key combination ALT + F11 leads us directly into the area of the
editor. In the recorded
macro, the syntax and logic of Excel can be analyzed. Change one or more values and you
can see the differences after restarting
• Absolute recording
A rigid recording, regardless of the current position of the cursor the same cells are
always addressed.
• Relative recording
Likewise a rigid recording, but the recorded macro will be executed from the cursor
position.
18
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
The non-empty parentheses, brackets with arguments, will be discussed later in the event
procedures.
The procedure mainly consists of two parts, which are listed below:
DDProcedure header or also the declaration part: Here the variables occurring in the
procedure are declared.
DDVBA code or program code: This is where all the music plays.
Depending on the setting, the term “Option Explicit” is visible. This forces us to declare
all variables that occur in procedures. We need to know in advance what variable a text is
and what a number is.
The macro recording is made via the menu command “Developer | Record Macro “.
Alternatively, the switch on the VISUAL BASIC toolbar can be used.
19
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
When the recording is started, the Record Macro dialog box appears. If you wish, we can
fill in the following information about the macro before starting:
After pressing the OK button, the recording is started. I have marked cells A1 through A5.
The list is shown in Figure 15.
The recording of a procedure is similar to a toddler who explores and gets to know its
surroundings by touching. Again, you learn the individual commands and their spelling.
We start our macro recorder via the menu “Developer | Record macro “.
20
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
First
3.1.3 we mark Recording
the area “A1: C4”, then we call the mask “Format cells”. There we define
Example
the settings in the “Numbers” tab to three decimal places, in the “Font” tab to “Bold” and
aWe
fontstart
sizeour “16”. recorder via the menu "Developer | Record macro ".
of macro
First we mark the area "A1: C4", then we call the mask "Format cells". There we define the settings
in the "Numbers" tab to three decimal places, in the "Font" tab to "Bold" and a font size of "16".
Sub Macro_reckording()
'Macro1 Macro
'Example for Reckording a macro.
'Keyboard Shortcut: Ctrg+b
Range("A1:C4").Select
Selection.NumberFormat = "0.000"
With Selection.Font
.Name = "Calibri"
.FontStyle = "Fett"
.Size = 16
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
End Sub
Unmodified formatting will either have the default settings or they will have the following entries,
such as "False";
Unmodified "XlNone";
formatting "XlAutomatic";
will either "0";
have the default or "None"
settings or theyending. These
will have the unnecessary
following additional
entries make our macros longer and more confusing.
entries, such as “False”; “XlNone”; “XlAutomatic”; “0”; or “None” ending. These unnecessary
Now we adapt
additional ourmake
entries record
ourregarding clarity:and more confusing.
macros longer
Sub Macro_recording()
Now we adapt our record regarding clarity:
Range("A1:C4").Select
Selection.NumberFormat = "0.000"
'Tap font
With Selection.Font
.FontStyle = "Fett"
.Size = 16
End With
End Sub
21
Unmodified formatting will either have the default settings or they will have the following entries,
such as "False"; "XlNone"; "XlAutomatic"; "0"; or "None" ending. These unnecessary additional
entries make our macros longer and more confusing.
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
Sub Macro_recording()
Range("A1:C4").Select
Selection.NumberFormat = "0.000"
'Tap font
With Selection.Font
.FontStyle = "Fett"
.Size = 16
End With
End Sub
An absolute recording rigidly formats certain areas. A relative recording is started from the
current cell.
We can use the previous absolute record as an example. We will now convert it into a
3.1.4 Change an absolute recording to a relative recording
relative record. For this purpose, the statement ActiveCell is entered in front of the range
(“D10: F12”)recording
An absolute Select therigidly
statement and certain
formats rewrite areas.
the range to “A1:recording
A relative C3”. is started from the current
cell.
The ActiveCell statement places the zero point in the active cell. The first column on the
We can use the previous absolute record as an example. We will now convert it into a relative record.
right is theoretically
For this purpose, thecolumn A, then
statement column Bisand
ActiveCell so on.inThe
entered same
front rule range
of the applies("D10:
to the F12")
lines. Select the
statement and rewrite the range to "A1: C3".
The ActiveCell statement places the zero point in the active cell. The first column on the right is
theoretically column A, then column B and so on. The same rule applies to the lines.
Absolute Recording
Absolute Recording
Sub Makro_Recording()
Range("D10:F12").Select
.
.
.
End Sub
I would like to repeat my adage: the more we record and analyze the recording, the more we master
IVBA programming.
would like to repeat my adage: the more we record and analyze the recording, the more
we master VBA programming.
22
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
There are two types of records: an absolute and a relative record. As described in the previous
3.1.5 absolute
chapter, Absolute
recordings or Relative
always Recording
address the same cells.
3.1.5 Absolute or Relative Recording
The relative
There are tworecording is recorded
types of records: like the absolute
an absolute and recording.
a relative The onlyAsdifference
record. describedis in
that
the previous
chapter,
the button absolute recordings always address the same cells.
There are “Use relative
two types records: anisabsolute
of references” selected and
before the recording.
a relative record. As described in the previous
chapter, absolute recordings always address the same cells.
The relative recording is recorded like the absolute recording. The only difference is that the button
"Use relative references" is selected before the recording.
The relative recording is recorded like the absolute recording. The only difference is that the button
"Use relative references" is selected before the recording.
Now a macro with the same content and with different recordings.
Figure 17: Starting of “Use Relative References“
Figure 17:area
• The Starting of “Use
D10: F12 Relative
has been References“
marked
Now a macro with the same content and with different recordings.
• • The
Defined with aF12
area D10: yellow background
has been markedcolor
Now a macro with the same content and with different recordings.
• Defined with a yellow background color
• The area D10: F12 has been marked
In the• absolute
Defined recording,
with a yellowregardless of thecolor
background cursor position, the areas D10: F12 are always
In the absolute recording, regardless of the cursor position, the areas D10: F12 are always marked
marked and formatting is performed.
and formatting is performed.
In the absolute recording, regardless of the cursor position, the areas D10: F12 are always marked
and formatting is performed.
Sub Absolute_recording()
' Absolute_recording macro
Sub Absolute_recording()
Range("D10:F12").Select
' Absolute_recording macro
With Selection.Interior
Range("D10:F12").Select
.Pattern = xlSolid
With Selection.Interior
.Color = 3
.Pattern = xlSolid
End With
.Color = 3
Range("D10").Select
End With
End Sub
Range("D10").Select
End Sub
In the relative record, starting at the cursor position, the next three column cells and the next three
In
rowthe relative
cells record, and
are marked starting at the is
formatting cursor position, the next three column cells and the
performed.
In the relative record, starting at the cursor position, the next three column cells and the next three
next three row cells are marked and formatting is performed.
row cells are marked and formatting is performed.
Sub Relative_recording()
' Relative_recording macro => show Figure 18
Sub Relative_recording()
ActiveCell.Range("A1:C3").Select
' Relative_recording macro => show Figure 18
With Selection.Interior
ActiveCell.Range("A1:C3").Select
.Pattern = xlSolid
With Selection.Interior
.Color = 3
.Pattern = xlSolid
End With
.Color = 3
ActiveCell.Select
End With
End Sub
ActiveCell.Select
End Sub
23
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
In order to remove an entire module in the VBA, this must be selected and then removed
either via Variant_1 or Variant_2, from figure 20. The query “Do you want to export
Modul1 before removing it?” Has to confirm with “No”.
24
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
For export, we proceed as if for deletion. Only now, the delete query will be answered with
“Yes”. The exported macro is saved as a basic file * .bas.
These or similar basic files can be imported again at any time. To do this we select the
menu command File | Import File” or the shortcut “Ctrl + M”.
25
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
If you have not already done so, we can define a keyboard shortcut when starting a macro.
Later, this macro can also be opened with this combination. This assignment can be written
with uppercase or lowercase letters.
26
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
Such buttons can be created from a toolbar of the form, the Autoforms, or the controls
Toolbox.
Download now
27
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
“Workbook_open ()” event is stored in the editor of “ThisWorkbook”. Here I will only
give a short explanation with figure 24. We will see futher examples later.
28
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro
The “Application.Run” statement will open a macro or function from an external Excel file.
The security settings are an important topic in Excel. Any open Excel file may contain
dangerous macros. Therefore, it is recommended to set the security setting to at least the
middle position. When set, it will open a dialog box when opening an Excel file that
contains macros. In it we can still decide whether to open the file call with or without
macro activation.
You get these when the menu command “Developer | Macro Security “is displayed. The
Security dialog allows you to create different settings.
29
EXCEL VBA: INTRODUCTION Script concept by VBA
VBA Visual Basic for Applications is an object-oriented macro programming language with
a very extensive set of functions and instructions for creating stand-alone programs.
With the VBA programming we can extensively exhaust the possibilities of Excel. Reasons
for this can be the following:
As you know, the way to love is through the stomach. This analogy includes vegetables, meat,
fish, a few different spices, and so on to other ingredients. All these ingredients are mixed
according to our wishes in a specific order to make a hopefully delicious meal out of it.
The path to VBA programming is through macro recording. During macro recording, all
activities of the user are recorded.
With VBA, we can address from the top level down to the lowest level. These levels are:
30
4.1 Procedure, Module, VBA-Code
We have
EXCEL VBA: already seen the
INTRODUCTION chapter contents in chapter 1. Here weScript
will see it again
concept briefly, as the
by VBA
following topics are built on it. Procedures are groups of instructions and have a solid framework. I
refer to it as the "head and foot" of the VBA program.
They start with the statement Sub Name_Procedure () and end with End Sub:
4.1 start
They Procedure, Module,
with the statement Sub VBA-Code
Name_Procedure () and end with End Sub:
4.1 Procedure,
We have
Sub already seenModule,
Say_hello_1() the chapterVBA-Code
contents in chapter 1. Here we will see it again briefly, as the
following topics are built on it. Procedures are groups of instructions and have a solid framework. I
referhave
We to‘You
it already
ascan
thewrite
"head and
seenVBA foot" of the
thecommand
chapter VBA program.
here
contents in chapter 1. Here we will see it again briefly, as the
following topics are built on it. Procedures are groups of instructions and have a solid framework. I
TheySub
End
refer start
to it aswith
thethe statement
"head Sub
and foot" ofName_Procedure
the VBA program.() and end with End Sub:
Sub Say_hello_1()
They start with the statement Sub Name_Procedure () and end with End Sub:
4.1.1
Sub Syntax
‘You can ofcommand
write VBA
Say_hello_1() VBA-Code
here
4.1.1 SYNTAX OF VBA-CODE
End Sub
‘You can write VBA command here
An instruction
An instruction isis aa syntactic
syntactic command
commandfor fordefinitions,
definitions,declarations
declarationsororoperations.
operations.These
Theseinstructions
can be grouped by shifting, making them easier to check. By indenting, the listing can be presented
End Sub
instructions can be grouped by shifting, making them easier to check. By indenting, the
in a clearer, more structured way. The more we click on indent, the more indentation. The reverse
listing canis be
function presented
with outdent.in a clearer,
This allows, more structured
for example, way.
With The With;
… End more For
we …click on Ifindent,
Next; … End If; Select
4.1.1
… End Select, Syntax
to become of
muchVBA-Code
clearer.
the more indentation. The reverse function is with outdent. This allows, for example, With
…4.1.1
An End
You canWith;
instruction Syntax
For
is a …
do this of IfVBA-Code
Next;
syntactic
with icons … the
End Edit
command
in If;
forSelect … inEnd
definitions,
toolbar Select,
VBA toEditor.
declarations
the become much
With theclearer.
or operations. These
optioninstructions
"Enlarge
can be groupedthe
indentation" by current
shifting, line
making them easier
or several markedto check.
lines By
areindenting,
moved tothe thelisting canwith
right, be presented
"Reduce
in ainstruction
An clearer, more
indentation" the structured
is alines way. to
are movied
syntactic command The more
the
for left. we click declarations
definitions, on indent, the or more indentation.
operations. These The reverse
instructions
You
can
can
function
do this with
be grouped
iconsThis
is with outdent.
by shifting,
in making
the Edit toolbar
allows,them
in the VBA
for example,
easier to With
check.
Editor.
… By
With the …
Endindenting,
option
With; Forthe Next;
“Enlarge
listingIfcan
… End If; Select
be presented
indentation”
… End
in the
Select,more
a clearer, current
to become line
much
structured or several
The marked
clearer.
way. more we lines areonmoved
click to the
indent, the right, with “ReduceThe reverse
more indentation.
function is with outdent. This allows,
indentation” the lines are movied to the left. for example, With … End With; For … Next; If … End If; Select
You
… Endcan do this
Select, with icons
to become muchinclearer.
the Edit toolbar in the VBA Editor. With the option "Enlarge
indentation" the current line or several marked lines are moved to the right, with "Reduce
indentation"
You can 26:
Figure the lines
do Indenting
this with are
iconsmovied
(Tab) to the
Editleft.
in/ Outdenting
the toolbar in the VBA Editor. With the option "Enlarge
(Shift+Tab)
indentation" the current line or several marked lines are moved to the right, with "Reduce
indentation"
An example with theoutdenting:
lines are movied to the left.
'Outdenting
Figure 26: Indenting (Tab) / Outdenting (Shift+Tab)
For x = 1 To 5
If Figure
name =26: Indenting
"Harun" Then (Tab) / Outdenting (Shift+Tab)
Range("A" & x).Value = name & "_" & x
An example with outdenting:
An
Else example with outdenting:
Figure 26: Indenting (Tab) / Outdenting (Shift+Tab)
Range("B" & x).Value = name & "_" & x
'Outdenting
End
An If
example with outdenting:
Next x= 1 To 5
For x
If name = "Harun" Then
'Outdenting
Range("A"
An
For example &with
x = 1 To x).Value
5 = name & "_" & x
indenting:
Else
If name = "Harun" Then
Range("B" & x).Value = name & "_" & x
'Indenting
Range("A"
EndxIf= 1 To 5
For
Else
Next x
If name
Range("B" =&"Harun"
x).ValueThen
= name & "_" & x
EndRange("A"
If & x).Value = name & "_" & x
AnElse
Next example
x with indenting:
Range("B"
An example with & x).Value = name & "_" & x
indenting:
'Indenting
AnEnd If
example with indenting:
For x x= 1 To 5
Next
If name = "Harun" Then
'Indenting
ForRange("A"
x = 1 To 5& x).Value = name & "_" & x
Else
If name = "Harun" Then
Range("B" & x).Value = name & "_" & x
Range("A"
End If
Else
Next x
Range("B" & x).Value = name & "_" & x
End If
Next x
31
EXCEL VBA: INTRODUCTION Script concept by VBA
The VBA code for names of subs, functions or variables can be written case insensitive.
As soon as a line is finished, VBA converts the first letters of the commands, functions,
arguments into uppercase letters.
Methods are enumerations in parentheses of a function. They are separated in Excel with
the semicolon. In VBA syntax, however, they are separated by a comma.
For this an example function “COUNTIF ()”: Between the brackets, you first enter the range
and then the searched term. They are separated by “;”. In VBA, however, with “,” separated.
The term “Stuttgart” should be counted in column C of an Excel spreadsheet. The result
should appear in cell “D1”.
In Excel:
¾¾ =CountIf(C:C;”Stuttgart”)
In VBA:
Sections of text starting with an apostrophe are marked as comments by the VBA editor.
They are not executed.
Lines can be summarized either individually or as a comment area. Simply mark the area
and select the option “Comment out block”.
32
Sections of text starting with an apostrophe are marked as comments by the VBA editor. They are
not executed.
You can
EXCEL add
VBA: your comments
INTRODUCTION as a line or at the end of a statement. Script concept by VBA
Lines can be summarized either individually or as a comment area. Simply mark the area and select
the option "Comment out block".
The editor writes program sections with individual commands, definitions and comments
according to VBA syntax rules. The first few letters of a command immediately display the
IntelliSense collection as a pop-up appear. Even if you have entered an object with a period,
this IntelliSense list or a selection window will display the possible commands, methods,
or properties for that object. That is a relief in programming.
33
EXCEL VBA: INTRODUCTION Script concept by VBA
The IntelliSense collection also appears after an equals sign of an object, but constants are
offered this time.
Quick help for the syntax of functions, methods or procedures is a good help. If, for example,
a method is entered, a short reference with the necessary and possible arguments appears
directly below the insertion point after entering the next empty space or an open parenthesis.
The arguments in square brackets are optional. All others are to be entered.
¾¾ Example 1:
The tooltip of “Offset” tells us that after an open parenthesis all necessary arguments are
listed. Commonly needed arguments are in parentheses and the currently needed argument
is shown in bold type.
¾¾ Example 2:
34
EXCEL VBA: INTRODUCTION Script concept by VBA
If you run your procedure step-by-step with F8, you will also get tool tips for the current
VBA line. This is marked in color by positioning the mouse pointer.
In the following example, the variable “Response” is assigned the address of the active cell.
When we move the mouse pointer to “answer”, the assigned value appears as a tooltip.
Long or very long VBA instruction lines can’t always be avoided in the VBA editor. A space
combined with an underscore helps us to present our programming in a more structured
way. The underscore is entered immediately after the space. This tells the VBA editor that
the statement line has not yet ended.
This has the advantage that the entire VBA line is visible. However, the break can’t
happen anywhere. It is only allowed in front of or behind an element of expression.
No comment may be inserted after the underscore. Sequences in strings must be terminated
with a quotation mark and linked with the join operator “&” and is called concatenation.
This can combine two or more strings to from a new string.
35
It is only allowed in front of or behind an element of expression.
No comment may be inserted after the underscore. Sequences in strings must be terminated with a
quotation mark and linked with the join operator "&" and is called concatenation. This can combine
two orVBA:
EXCEL moreINTRODUCTION
strings to from a new string. Script concept by VBA
Sub Example_VBA_Syntax_gap()
Dim strName, strfirstname, strAddress As String
strname=”Max”
strfirstname=”Mustermann”
straddress=”Musterstrasse 12” & chr(10) & “70000 Stuttgart”
'Without gap
MsgBox ("Name: " & strname & Chr(10) & "First Name: " & strfirstname & Chr(10) & "Address: " &
straddress)
'With gap
MsgBox ("Name: " & strname & Chr(10) & _
"First Name: " & strfirstname & Chr(10) & _
"Adresse: " & straddress)
End Sub
The properties of the variables are set at the beginning of the procedure with the Dim
4.2 Variable, constant and date type
keyword. These definitions can be numerical values, texts or objects.
Variables are placeholders for numbers, texts, objects and can be changed in the macro process.
Variables are used in each programming language so that your values can be recorded during
program
The execution
naming and, if necessary,
of the variables used
follows the later orrules:
following taken over by another (sub) procedure.
The properties of the variables are set at the beginning of the procedure with the Dim keyword.
These• definitions
It starts with
can abeletter
numerical values, texts or objects.
• It can be up to 255 characters long
The naming of the variables follows the following rules:
• • ItItstarts
contains
withno dots, minus signs, spaces or special characters
a letter
• It can be up to 255 characters long
• It contains no dots, minus signs, spaces or special characters
The variable abbreviations are set by us, but they also indicate their origin. For example,
an integer
The number
variable with “intNumber”
abbreviations are set by means
us, butthat
theythe variable
also number
indicate belongs
their origin. toexample,
For the type an integer
number with "intNumber" means that the variable number
integer. Let’s take a look at a procedure that uses them: belongs to the type integer. Let’s take a
look at a procedure that uses them:
Sub Use_prefixe()
Dim intNumber As Integer
Dim strName As String
Dim blnAntwort As Boolean
Dim bytValue As Byte
intNumber = 231
strName = "Harun"
blnAntwort = True
bytValue = 1
End Sub
This is very helpful in debugging, since variable types declared by these abbreviations can be detected
faster. Depending on the declaration type and the declaration location, these variables have a scope
that we will look at before presenting the individual variable types.
36
EXCEL VBA: INTRODUCTION Script concept by VBA
This is very helpful in debugging, since variable types declared by these abbreviations can
be detected faster. Depending on the declaration type and the declaration location, these
variables have a scope that we will look at before presenting the individual variable types.
4.2.1 DATE-TYPE
Data types are groupings of data. These are all kinds of numbers, texts, etc. They are declared
at the beginning of the procedure. They are not always necessary for smaller procedures,
but are often used in longer procedures or projects with multiple programming.
In other words, there are many worksheets, that is, worksheets (plural). These belong to
the species worksheet, so worksheet (singular).
You can declare it named arbitrarily. In the example “Number1” and “Number2” are
declared as Integer, and “Number3” and “Number4” are declared as Long. When used in
a procedure, they would not be unique, which are integer type and which are long type.
It is better if you can immediately recognize what type of data it is. Therefore, before each
variable we have an abbreviation, prefix with:
37
EXCEL VBA: INTRODUCTION Script concept by VBA
38
EXCEL VBA: INTRODUCTION Script concept by VBA
Sub Date_type()
'With Dim declared
Dim curValuel As Currency
Dim blnValue_3 As Boolean
Dim datDate, datDate_1 As Date
'With Static declared
Static strText_1 As String * 5
Static intValue_1 As Integer
'
curValue = 250 / 3
intValue_1 = 250 / 3
Value_2 = 250 / 3
'
blnValue_3 = 250 / 3 < 5 * 5
'
strText = "ABCDEFsdasd"
strText_1 = "ABCDEFsdasd"
'
datDate = #5/25/1964#
datDate_1 = Date
Debug.Print "The variable has the value as Currency " & curValue
Debug.Print "The variable has the value as Integer " & intValue_1
Debug.Print "The variable has the value without declaration " & Value_2
Debug.Print "The variable has the value as Boolean " & blnValue_3
Debug.Print "The variable has the value as String " & strText
Debug.Print "The variable has the value as String with five characters " & strText_1
Debug.Print "The variable has the value as Date " & datDate
Debug.Print "The variable has the value as Date " & datDate_1
'
End Sub
The next example reads the range A1: C4 and prints in the immediate area.
39
EXCEL VBA: INTRODUCTION Script concept by VBA
The next example reads the range A1: C4 and prints in the immediate area.
Sub Date_type_2()
Dim intX, intY As Integer
Dim objWS As Object
Set objWS = Worksheets("Sheet1")
For intX = 1 To 4
For intY = 1 To 3
Debug.Print "Array-Range " & objWS.Cells(intX, intY)
Next intY
Next intX
End Sub
Prefixes are abbreviations that can be used at the beginning of variable names. There are
fixed and variable abbreviations. The built-in constants have fixed abbreviations that indicate
their origin. For example:
• vb from VBA-Object-Library
• xl from Excel
• fm from MSForms-Library
• mso from MS-Office
• grd from Toolbox-Sheet.
40
EXCEL VBA: INTRODUCTION Script concept by VBA
In procedures and functions, a simple dim statement is sufficient for declaring a variable. The
declared variable is only valid in the current procedure or function. We call it a “local variable”.
The figure above shows two procedures in “Module1” with an output of the first procedure.
We have declared the variable “intValue” in procedure “Gültigkeitsbereich_1” and the variable
“strText” in procedure “Validity_Range _2”.
“IntValue” only applies in the upper procedure and “strText” only in the lower procedure.
Validity within a module means that a variable is valid in all procedures. This variable is
declared outside the procedures.
41
EXCEL VBA: INTRODUCTION Script concept by VBA
The instruction “Dim intValue3 As Integer” declares the variable “intValue3” in the module
Figure 36: Validity within a module, therefore in all procedures
header. Procedures with inter-procedurally valid variables can also be used with the private
keyword. The procedure
The instruction “Validity_Range_4”
"Dim intValue3 As Integer" and “_5” the
declares could also be"intValue3"
variable edited withinthe private
the module header.
Procedures with inter-procedurally valid variables can also be used with the private keyword. The
keyword:
procedure "Validity_Range_4" and "_5" could also be edited with the private keyword:
Download now
42
EXCEL VBA: INTRODUCTION Script concept by VBA
Passing a variable between procedures or between a procedure and a function is also possible.
The variable to be passed is entered with a declaration in parentheses after the designation.
We can look at the first procedure in figure 37. To calculate the circular area from a
radius, we pass the radius, here 5 mm, with the line SubProgramm (5) to the procedure
“SubProgramm”. The calculated value is output formatted in the procedure “SubProgramm”.
Now let’s look at a function. Here we calculate the circular area by passing the radius with
the line “dblResult = Calculation (5)” to the “Function dblCalculation”. The calculated
value is output in the procedure “dblCalculatation”.
If the variables are to be valid in all modules, then we declare these variables, for example
in module1, with the Public statement. That is, these variables are provided by all modules
in all procedures.
43
EXCEL VBA: INTRODUCTION Script concept by VBA
Our example: We write in module4 “Bsp_Public_Modul1” and declare the variables outside
the procedure with the Public statement as “Public Value1, Value2, Result As Integer”.
We copy this procedure and insert it in module1 and in table1 (table1). We adapt the with
the module names. In module1 this is called “Public_module1”, in module2 “Public_module2”
and in Sheet1 “Public_Sheet”.
Variables with a Static statement retain their values even when the procedure is finished.
By contrast, variables with a Dim statement start from the beginning.
Our example below “Main_Sub” calls the procedures “Normal_Procedure” and “Static_
Procedure” five times in succession.
In “normal_procedure”, the x value with the Dim statement is defined as “Dim x As Integer”.
In the “static_procedure” procedure, the y value is defined using the static statement, “Static
y As Integer”.
Let’s go through “MainSub” twice in a row. The x value always stays at “1” and the y value
becomes “1” higher.
44
EXCEL VBA: INTRODUCTION Script concept by VBA
What is the second run? The x value will still remain “1” and the y value will continue to
increase by “1”.
So far we have declared our variables with the Dim statement. Such variables are provided
by either an input or a result of calculation or the like.
The Set-variables, on the other hand, are fixed components of the excel.
45
4.2.9 Set Variable of object
So far we have declared our variables with the Dim statement. Such variables are provided by either
So far we have declared our variables with the Dim statement. Such variables are provided by either
an input or a result of calculation or the like.
an input or a result of calculation or the like.
The Set-variables,
EXCEL on the
VBA: INTRODUCTION otherhand,
The Set-variables, on the other hand, are
are fixed
fixed components
components of the
of the excel.
Script concept by VBA
excel.
Such Excel
Such Excelobjects
objectsare:
are:
VBA•• syntax
Cells/starts
Cells with
/Ranges
Ranges ofofSet, followed
a atable
table by Object variable, then Excel object type.
(Range);
(Range);
• All diagrams
• All diagrams(Charts),
(Charts),tables
tables (Worksheets);
(Worksheets);
An example:
•• All folders
All folders(Workbooks);
(Workbooks);
•• Forms.
Forms.
¾¾ Set objWS = Worksheets(“Sheet1”)
VBA syntax
VBA syntaxstarts
startswith
withSet,
Set,followed
followed
byby Object
Object variable,
variable, then
then Excel
Excel object
object type.
type.
An …
An example:
example:
¾¾ Set objWS = Nothing
➢➢ Set
SetobjWS
objWS==Worksheets("Sheet1")
Worksheets("Sheet1")
……
These
➢➢ variables
Set
SetobjWS make
objWS accessing objects easier
==Nothing
Nothing and faster.
These
These variables
variablesmake
makeaccessing
accessingobjects
objectseasier and
easier faster.
and faster.
Here is our example with and without a set variable:
Here is our example with and without a set variable:
Here is our example with and without a set variable:
We
We have two tables,
tables, "Sheet1"
“Sheet1” and
and"Sheet2".
“Sheet2”.Cell
Cell"A1"
“A1”
of of Sheet1
Sheet1 hashas
thethe value
value “1923”.
"1923". It
It should be
We have two tables, "Sheet1" and "Sheet2". Cell "A1" of Sheet1 has the value "1923". It should be
multiplied
should by the value
be multiplied "2.5"
by "2.5"and the
the value product
“2.5” entered
and the in cell
product "A1" of
entered table2.
multiplied by the value and the product entered in cell "A1"inof cell “A1” of table2.
table2.
Sub Exaple_without_Set()
Sub Exaple_without_Set()
Worksheets("Sheet1").Range("a1").Value = 1923
Worksheets("Sheet1").Range("a1").Value
Worksheets("Sheet2").Range("a1").Value = = 1923
Worksheets("Sheet1").Range("a1").Value * 2.5
Worksheets("Sheet2").Range("a1").Value
End Sub = Worksheets("Sheet1").Range("a1").Value * 2.5
End Sub
46
EXCEL VBA: INTRODUCTION Script concept by VBA
The user-defined data types are assembled from the basic types listed above using the Type
statement.
4.2.10 TheyUser-defined
are listed between date
the following
type keywords:
The user-defined data types are assembled from the basic types listed above using the Type
DDPrivate
statement. They(valid only where
are listed they
between thehave been defined)
following keywords:and
Private (valid only where they have been defined) and
DDPublic (cross-procedures, that means they apply in all procedures).
Public (cross-procedures, that means they apply in all procedures).
Option Explicit
The constants are fixed, predefined numbers or strings. The contents of the constants do not
change during the duration of the procedure. The use of constants allows easier handling of
values. They also lead to a better readability of a macro. They are defined directly at the beginning
of the procedure with the Const statement. Then follow the name and the value assignment.
Variables can also be used instead of constants, but our macro becomes too confusing.
WithConst we say that this definition is not changeable!
47
during the duration of the procedure. The use of constants allows easier handling of values. They also
lead to a better readability of a macro. They are defined directly at the beginning of the procedure
with the Const statement. Then follow the name and the value assignment.
4.2.11 Statement Const – unchanged value -
EXCEL VBA: can
Variables INTRODUCTION
also be used Script too
instead of constants, but our macro becomes concept by VBAWith Const
confusing.
The constants are fixed, predefined numbers or strings. The contents of the constants do not change
we say that this definition is not changeable!
during the duration of the procedure. The use of constants allows easier handling of values. They also
lead to a better readability of a macro. They are defined directly at the beginning of the procedure
Sub Constants_1()
with the Const statement. Then follow the name and the value assignment.
‘VAT
Const VAT As Single = 0.19
Variables can also be used instead of constants, but our macro becomes too confusing. With Const
'Filename
we say that this definition is not changeable!
Const Filename As String = "Constant.xlsx"
Const strPath As String = "C:\Harun\"
Sub Constants_1()
Const strPath_all As String = "C:\Harun\Constant.xlsx"
‘VAT
'Dim's
Const VAT As Single = 0.19
Dim Value_1 As Integer
'Filename
Dim Text_1 As String
Const Filename As String = "Constant.xlsx"
Value_1 = 2321
Const strPath As String = "C:\Harun\"
Text_1 = "Text Text"
Const strPath_all As String = "C:\Harun\Constant.xlsx"
Debug.Print "VAT is: " & vbCr & VAT & "%" & Chr(10)
'Dim's
Debug.Print "File name is: " & Chr(13) & Dateiname & vbLf
Dim Value_1 As Integer
Debug.Print "Path is: " & vbCr & Pfad & Chr(10)
Dim Text_1 As String
Debug.Print "Path & file name is: " & vbCr & strPath_all & vbLf
Value_1 = 2321
Debug.Print "Path & file name is: " & vbCr & strPath & filename & vbLf
Text_1 = "Text Text"
Debug.Print "Value is: " & Chr(13) & Value_1 & vbLf
Debug.Print "VAT is: " & vbCr & VAT & "%" & Chr(10)
Debug.Print "Text is: " & Chr(13) & Text_1 & vbLf
Debug.Print "File name is: " & Chr(13) & Dateiname & vbLf
End Sub
Debug.Print "Path is: " & vbCr & Pfad & Chr(10)
Debug.Print "Path & file name is: " & vbCr & strPath_all & vbLf
Debug.Print "Path & file name is: " & vbCr & strPath & filename & vbLf
Debug.Print "Value is: " & Chr(13) & Value_1 & vbLf
If we write like this below, we will get an error message.
Debug.Print "Text is: " & Chr(13) & Text_1 & vbLf
A const value must not be changed. This procedure works
End Sub
with Dim VAT As Integer:
If we write like this below, we will get an
error
Sub message. A' const value must not be
Constants_2()
Const VAT As Single = 0.19
changed. This
If we write likeprocedure works
this below, with
we will getDim
an error message.
VAT=VAT + 1
A
VAT const value
As VAT must
Integer: not be changed. This procedure works
MsgBox
with Dim VAT As Integer:
End Sub
Sub Constants_2() '
Const VAT As Single = 0.19
VAT=VAT + 1
MsgBox VAT
End Sub
There are also many (system) integrated constants in VBA. They begin with the prefix
For example, the following color constants can be used directly throughout the code:
48
EXCEL VBA: INTRODUCTION Script concept by VBA
4.2.12 VBA constants
There are also many (system) integrated constants in VBA. They begin with the prefix
vb Visual Basic Constants Description
xl Excel.
vbBlack Black color
For example, the following color constants can be used directly throughout the code:
vbRed Red color
Constants Description
VbGreen Green color
vbBlack Black color
vbWhite White
Tablecolor
2: VBA constants
Table 2: VBA constants
In this example, the active cell is displayed with a green background color.
In this example, the active cell is displayed with a green background color.
Sub VBA_Constant()
ActiveCell.Interior.Color = vbGreen
End Sub
Download now
49
EXCEL VBA: INTRODUCTION Script concept by VBA
Sub Addition_Subtraction()
Dim x, y, z, xy, xyz As Integer
Dim a, b, ab As Single
x = 234
y = -123
a = Range("A1").Value '12,5
b = Range("B1").Value '25,7
z = (x - y) + 35
* Multiplication
/ Division
\ Division (Integer, without comma)
^ Potency
Mod Modulo
The calculate rule says: "Point before line". This means multiplication and division first, then addition
and subtraction. This regulation also applies in VBA.
12 + 3 * 5 = 27 50
EXCEL VBA: INTRODUCTION Script concept by VBA
* Multiplication
/ Division
\ Division (Integer, without comma)
^ Potency
Mod Modulo
The calculate rule says: “Point before line”. This means multiplication and division first,
then addition and subtraction. This regulation also applies in VBA.
12 + 3 * 5 = 27
Comparison operators can be applied to almost all data types. The result of the comparison
is a truth value - either
DDTRUE correct,
DDFALSE not correct.
Comparison operations can be performed in the VBA using the following operators:
Operator Description
< less than
<= less than or equal to
> more than
>= more than or equal to
= equal
<> unequal
Is compare an object
Like compare a pattern
51
<= equal
less than
<> less
<= unequal
than or equal to
>Is compare
more than an object
Like
>= compare
more than aorpattern
EXCEL VBA: INTRODUCTION
equal to Script concept by VBA
= equal
<> is an
Well, here unequal
example of IS or LIKE:
Is compare an object
• IS is used to compare two different variables with references to object.
• IS is Like compare
used to compare a pattern
two different variables with references to objects.
In addition to mathematical and comparison operators, there are logical operators. The
result is output with a Boolean expression.
52
Not performs a logical negation of an expression.
And serves to perform a logical conjunction between two expressions.
Or is used to perform a logical disjunction between two expressions.
Xor VBA:
EXCEL is used to perform a logical exclusion between two expressions.
INTRODUCTION Script concept by VBA
Eqv is used to determine a logical equivalence between expressions.
Imp serves to perform a logical implication between two expressions.
The emergency operator only affects operands, all other logical operators become Linking
The emergency operator only affects operands, all other logical operators become Linking
expressions.
expressions.
Sub Operators()
Value1 = 1
Value2 = 5
Value3 = 10
Result = Not (Value1 < Value2) 'results False
Result = (Value2 > Value1) And (Value3 > Value2) results True
Result = (Value2 < Value1) Or (Value3 < Value2) 'results False
Result = (Value2 < Value1) Xor (Value3 > Value2) 'results True
Result = (Value2 < Value1) Eqv (Value3 < Value2) 'results True
Result = (Value2 > Value1) Imp (Value3 < Value2) 'results False
End Sub
53
EXCEL VBA: INTRODUCTION Errors in VBA
5 ERRORS IN VBA
The errors can arise from different sources, for instance:
• Typing error
• missing or incorrect declarations
• infinite loops
• missing constant
• faulty separation of the VBA code line
• unauthorized / unexpected input / output or
• incorrect entry in the VBA line, etc.
In case of unauthorized or unexpected input, a runtime error appears with an error message
and error code. “Runtime error index out of range”.
There are also different reactions to these error messages. For example, in typing errors the
whole VBA code line will appear in red.
To avoid such error messages, the “Option Explicit” instruction is helpful. It is written at the
beginning in each module level. But then we have to declare each variable in the procedure
until all are declared. That could be a bit tedious in the beginning, but it helps a lot.
Option Explicit
Sub Missing_Variable()
'Variable “NewMessage” is missing
MsgBox (NewMessage)
End Sub
Figure 45: Missing Variable
Figure 45: Missing Variable Figure
54
EXCEL VBA: INTRODUCTION Errors in VBA
The information in the error message is unfortunately not very useful. With the button
“Debug” we get to the “faulty” VBA-code line which is highlighted in yellow. With the
“Help” button we get to the help text if something and understandable entered. This does
not usually help us find a solution. Unfortunately, we have to live with that. The “Finish”
button terminates or aborts the procedure depending on the error message.
In our example you will find two tables, “Harun” and “Kaplan”, which are not present. The
first mistake is corrected. In the table “Kaplan”, our error message appears again.
55
If necessary, On Error Resume Next can be deactivated with On Error Goto 0.
On Error Goto VBA-String line redirects the VBA code flow to the line.
EXCEL
In ourVBA: INTRODUCTION
example you will find Errors in
two tables, "Harun" and "Kaplan", which are not present. VBA
The first mistake
is corrected. In the table "Kaplan", our error message appears again.
Sub Worksheet_not_exist_2()
'Worksheet "Harun" does not exist!
On Error Resume Next
Worksheets("Harun").Activate
On Error Goto 0
'Worksheet "Harun" does not exist, too!
Worksheets("Kaplan").Activate
End Sub
Sub Worksheet_does_not_exist3()
'Worksheet "Harun" does not exist!
On Error GoTo Meldung
Worksheets("Harun").Activate
'
'other VBA-Code line
'
Meldung:
MsgBox " In case of error, I will be redirected here!"
End Sub
Now let’s have a look at the individual icons with their tasks.
56
EXCEL VBA: INTRODUCTION Errors in VBA
The macro can be executed in single step mode also named “Step by Step“.
The current line is marked on the left bar with a yellow arrow and the line is highlighted in yellow.
If you want to know the contents of the variable, just move the mouse pointer over the
variable. A tooltip displays the content of the variable.
When debugging in a single step, the current line is highlighted in yellow and marked with
a yellow arrow in the bar to the left of the code.
The Toggle breakpoint serves to stop the drain at this point. The activated line is marked
with a red dot. The line is saved with the same color.
The program automatically runs through to the breakpoint and stops at the breakpoint.
57
EXCEL VBA: INTRODUCTION Errors in VBA
5.3.4 BOOKMARKS
In order to be able to reach certain places more quickly, so-called bookmarks can be
inserted on the left bar. We go to the line and click on the flag icon “Bookmark” in the
toolbar “Edit”. A square appears with rounded corners on the bar.
The bookmark can be used multiple times.
The same icon is also used to disable individual bookmarks. You can jump between the
bookmarks with the other two flag symbols
58
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
6 PROGRAM SEQUENCE,
BRANCH UND LOOPS
An important VBA code part is the control of the program sequences depending on the
situation. The procedure should react differently depending on the determined value. It’s
like a traffic light. If green then drive and if red then stop, or if yellow then yield.
Or in other words: as long as nothing changes, this action is carried out; as soon as something
changes, the action is also changes.
6.1.1
For IIf Function
simpler decisions, there is the Iif decision. If we have only one decision, we can easily
For simpler decisions, there is the Iif Our
query them with the IIf function. decision. If wemay
example havelook
only like
one decision,
this: we can easily query them
with the IIf function. Our example may look like this:
Sub Movie_Ticket()
grade=InputBox(“Well, what grade did you get?“)
What if there is more decision-making criteria? Now several If..Then's are among themselves. This
What if there
variant is notisrecommended
more decision-making
because criteria? Now several
it will require a little If..Then’s are among
more typing. themselves.
Nevertheless, we can look at
this example:
This variant is not recommended because it will require a little more typing. Nevertheless,
we
Subcan look at this example:
if_statement_1()
grade =InputBox(“Well, what grade did you get?“)
If grade = 1 Then
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
End If
If grade = 2 Then
MsgBox “Great. Here is your movie ticket with popcorn. Have fun.“
Endif 60
If grade = 3 Then
End If
End Sub
The If statement has checked fixed notes on previous examples. If entered with a number, no correct
EXCEL VBA:would
message INTRODUCTION
appear. Program
Now we have made our example sequence,
even branch und
more accurate. loops
Here we have also
given the notes between 1 and 2, etc.:
Sub if_statement_2()
grade =InputBox(“Well, what grade did you get?“)
If grade > 1 And Note <2 Then
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
Elseif grade > 2 And Note < 3 Then
MsgBox “Great. Here is your movie ticket with popcorn. Have fun.“
ElseIf grade < 4 Then
If gradeMsgBox
<= 3 “Good,
Then here is your movie ticket. Have fun.“
Else
MsgBox “Good, here is your movie ticket. Have fun.“
MsgBox “You should still learn. Sorry.“
Else
End If
IfMsgBox
End grade <=
Sub
“Sorry.“
3 Then
End If
MsgBox “Good, here is your movie ticket. Have fun.“
End Sub
Else
MsgBox “Sorry.“
We
Whatcan stack them like a matryoshka nesting doll. Compared to the previous example,
EndifIfthere is more decision-making criteria? Now several If..Then's are among themselves. This
variant
there is is
End Sub not recommended
a little because
less typing. Now it willexample
the same require stacked
a little more
with typing.
Elseif: Nevertheless, we can look at
this example:
What if there is more decision-making criteria? Now several If..Then's are among themselves. This
Sub if_statement_1()
variant is not recommended because it will require a little more typing. Nevertheless, we can look at
grade =InputBox(“Well, what grade did you get?“)
this example:
If grade = 1 Then
SubMsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
if_statement_1()
End If
grade =InputBox(“Well, what grade did you get?“)
If
If grade
grade = =21 Then
Then
MsgBox
MsgBox “Great. Here
“Great. Here is
is your
your movie
movie ticket
ticket with
with popcorn. Have
popcorn and icefun.“
cream. Have fun.“
Endif
End If
If
If grade
grade = =32 Then
Then
MsgBox
MsgBox “Great.here
“Good, Hereisisyour
yourmovie
movieticket.
ticketHave fun.“
with popcorn. Have fun.“
Endif
Endif
If
If grade
grade > =33 Then
Then
MsgBox
MsgBox “Good,“You should still
here is learn.
your Sorry!“
movie ticket. Have fun.“
End
Endif If
End
If Sub
grade > 3 Then
MsgBox “You should still learn. Sorry!“
WeEnd canIf stack them like a matryoshka nesting doll. Compared to the previous example, there is a
little
The
End If less typing. has
statement
Sub Nowchecked
the same example
fixed stacked
notes on withexamples.
previous Elseif: If entered with a number,
no
Sub
correct message would appear. Now we have made our example even more accurate.
if_statement_with_Elseif()
We can stack them like a matryoshka nesting doll. Compared to the previous example, there is a
Here
grade we have also given what
=InputBox(“Well,
little less typing. Now the
the notes
grade
same
between
did you
example
1get?“)
and with
stacked
2, etc.:
Elseif:
If grade = 1 Then
SubMsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun. “
if_statement_with_Elseif()
Elseif grade = 2 Thenwhat grade did you get?“)
grade =InputBox(“Well,
If grade = 1 Then Here is your movie ticket with popcorn. Have fun.“
MsgBox “Great.
ElseIf“Great.
MsgBox grade = 3 Then
Here is your movie ticket with popcorn and ice cream. Have fun. “
MsgBox “Good, here is your movie ticket. Have fun.“
Elseif grade = 2 Then
ElseMsgBox “Great. Here is your movie ticket with popcorn. Have fun.“
MsgBox
ElseIf“You
gradeshould still learn. Sorry.“
= 3 Then
End If MsgBox “Good, here is your movie ticket. Have fun.“
End Sub
Else
MsgBox “You should still learn. Sorry.“
The If If
End statement has checked fixed notes on previous examples. If entered with a number, no correct
message
End Sub would appear. Now we have made our example even more accurate. Here we have also
given the notes between 1 and 2, etc.:
The If statement has checked fixed notes on previous examples. If entered with a number, no correct
Sub if_statement_2()
message would appear. Now we have made our example even more accurate. Here we have also
grade =InputBox(“Well,
given the notes betweenwhat
1 and grade did you get?“)
2, etc.:
If grade > 1 And Note <2 Then
SubMsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
if_statement_2()
Elseif grade > 2 And what
grade =InputBox(“Well, Note grade
< 3 Then
did you get?“)
If grade > 1 And Note <2 Then movie ticket with popcorn. Have fun.“
MsgBox “Great. Here is your
ElseIf “Great.
MsgBox grade <Here
4 Then
is your movie ticket 61
with popcorn and ice cream. Have fun.“
MsgBox “Good, here is your
Elseif grade > 2 And Note < 3 Then movie ticket. Have fun.“
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
The next example checks whether the input corresponds to a value, i.e. no letter or similar.
The next example checks whether the input corresponds to a value, i.e. no letter or similar. We check
We check this with IsNumeric:
this with IsNumeric:
Sub if_statement_3()
grade =InputBox(“Well, what grade did you get?“)
The next example checks
If IsNumeric(Note) Then whether the input corresponds to a value, i.e. no letter or similar. We check
thisIf with
grade IsNumeric:
> 1 And Note <2 Then
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
Sub if_statement_3()
Elseif grade > 2 And Note < 3 Then
grade =InputBox(“Well,
MsgBox “Great. Here whatis grade did you
your movie get?“)
ticket with popcorn. Have fun.“
If IsNumeric(Note) Then
ElseIf grade < 4 Then
If grade > 1 And
MsgBox Note here
“Good, <2 Then
is your movie ticket. Have fun.“
MsgBox
Else “Great. Here is your movie ticket with popcorn and ice cream. Have fun.“
Elseif grade
MsgBox “You>should
2 Andstill
Note < 3 Then
learn. Sorry.“
End If MsgBox “Great. Here is your movie ticket with popcorn. Have fun.“
Else ElseIf grade < 4 Then
MsgBox MsgBox
"Please“Good,
enter here
your is your movie ticket. Have fun.“
grade!!"
Else
End If
End MsgBox
Sub “You should still learn. Sorry.“
End If
Elsea practical example. We check the contents of a current cell. Depending on the content of the
Now
MsgBox
cell, "Please enter your grade!!"
Now ait practical
should output what
example. Wethe content
check is and has.
the contents of aThe output
current should
cell. be output
Depending according
on the contentto the type.
End If
of
End theSub
If the cell, it should
content containsoutput whatthen
a number, the acontent
messageis and
with has. The output
cell content should
appears. be output
Otherwise, if the content
according
contains atodate,
the type.
then another message with cell content appears, etc.
Now a practical example. We check the contents of a current cell. Depending on the content of the
cell,
Sub it should output what the content is and has. The output should be output according to the type.
Check_cell_value_1()
If the content contains a number,
If IsNumeric(ActiveCell) then a message
And ActiveCell with cell content appears. Otherwise, if
<> "" Then
If the MsgBox
content contains
"The a value
cell number,
is a then a message
number! " & with cell content appears. Otherwise, if the content
ActiveCell.Value
the content contains a date, then another message with cell content appears, etc.
contains a date,
ElseIf then another message
IsDate(ActiveCell) Then with cell content appears, etc.
MsgBox "The cell value is a date" & ActiveCell.Value
Sub Check_cell_value_1()
ElseIf ActiveCell <> "" Then
If IsNumeric(ActiveCell)
MsgBox "The cell And ActiveCell
value <> ""
is a Text!" & Then
ActiveCell.Value
MsgBoxElseIf
"TheActiveCell
cell value =
is ""
a number!
Then " & ActiveCell.Value
ElseIf IsDate(ActiveCell)
MsgBox "The current Then cell is empty!"
End IfMsgBox "The cell value is a date" & ActiveCell.Value
End Sub ElseIf ActiveCell <> "" Then
MsgBox "The cell value is a Text!" & ActiveCell.Value
ElseIf ActiveCell = "" Then
MsgBox "The current cell is empty!"
End If
End Sub
We divide the text to a variable “content”. The MsgBox statement, as seen several times,
issues this message. It is written at the end of the listing with the variable “content” AND
with active cell content.
62
With a refinement it may look like this:
We divide the text to a variable "content". The MsgBox statement, as seen several times, issues this
With a refinement
message. it may
It is written look
at the like
end of this:
the listing with the variable "content" AND with active cell content.
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
We divide
Firstly, thisthe text to and
is clearer a variable
secondly, "content".
it is moreTheadaptable
MsgBox statement, as seen several times, issues this
or adjustable.
message. It is written at the end of the listing with the variable "content" AND with active cell content.
I think it looks a bit clearer.
I think it looks a bit clearer.
Firstly, this is clearer and secondly, it is more adaptable or adjustable.
Sub Check_cell_value_2()
I think it looks a bit clearer.And ActiveCell <> "" Then
If IsNumeric(ActiveCell)
Inhalt = "The cell value is a number!"
Sub Check_cell_value_2()
ElseIf IsDate(ActiveCell) Then
If IsNumeric(ActiveCell)
Inhalt = "The cell value And isActiveCell
a date!" <> "" Then
Inhalt
ElseIf ActiveCell <> "" Thennumber!"
= "The cell value is a
ElseIf IsDate(ActiveCell)
Inhalt = "The cell value Thenis a text!"
Inhalt = "The cell value
ElseIf ActiveCell = "" Then is a date!"
ElseIf ActiveCell
Inhalt = "The <> "" Then
current cell is empty!"
End If Inhalt = "The cell value is a text!"
ElseIf ActiveCell =
MsgBox Inhalt & ActiveCell.Value"" Then
End Sub Inhalt = "The current cell is empty!"
End If
Another MsgBox Inhalt
practical & ActiveCell.Value
example:
End Subpractical example:
Another
In this example, the input is checked by number. If there is no number, then a message with "Enter
Another practical
number" and macro example:
will be terminated. If the input is a number, it is checked, then, depending on
thethis
In sizeexample,
of the input, the variables
the input is checked "a" and "b" are assigned
by number. If there values. These will
is no number, thenbe acalculated
message and spent
In the
at thisend
example, the input is checked by number. If there is no number, then a message with "Enter
accordingly.
with “Enter number” and macro will be terminated. If the input is a number, it is checked,
number" and macro will be terminated. If the input is a number, it is checked, then, depending on
then, depending
the size on the
of the input, size
the of the input,
variables "a" and the"b"
variables “a” andvalues.
are assigned “b” areThese
assigned
will values. These and spent
be calculated
at
Subthe end accordingly.
Practical_Example()
will be calculated and spent at the end accordingly.
intInput = InputBox("Please enter your number!")
If IsNumeric(intInput) = True Then
Sub Practical_Example()
If intInput < 5 Then
intInput
a == 2 InputBox("Please enter your number!")
If IsNumeric(intInput)
b=3 = True Then
If intInput < 5 Then
ElseIf intInput > 5 And intInput < 10 Then
a =a2= 4
b =b3= 5
ElseIf intInput > 10
ElseIf 5 AndAndintInput
intInput<<10 15Then
Then
a =6 4
b =7 5
ElseIf
End If intInput > 10 And intInput < 15 Then
Else a = 6
MsgBox b("Please
=7 enter your number!")
End
Exit Sub If
Else If
End
MsgBox ("Please
intResult = a * b enter your number!")
Exit Sub
MsgBox intResult
EndEndSubIf
intResult = a * b
MsgBox intResult
End Sub
63
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
If6.1.3 Select
multiple inputs Case-;
or values need End
to be Select
validated statement
and another event is to occur then “if
statements” may become
If multiple inputs cluttered.
or values need toIn be
thisvalidated
case we need
and precise
anotherinstruction.
event is toThis is the
occur thenSelect
“if statements”
may become cluttered. In this case we need precise instruction. This is
Case statement. Here the content of a variable is checked for a possible match. the Select Case statement.
Here the content of a variable is checked for a possible match.
Sub Select_Case_statement_I()
grade=InputBox(“Well, what grade did you get?“)
Select Case grade
Case 1
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun!“
Case 2
MsgBox “Great. Here is your movie ticket with popcorn. Have fun!“
Case 3
MsgBox “Good, here is your movie ticket. Have fun!“
Case 4
MsgBox “Alright. Exceptionally done. Here is your movie ticket! “
Case >= 5
MsgBox “You should still learn. Sorry! “
End Select
End Sub
Sub Select_Case_Anweisung_II()
grade =InputBox(“Well, what grade did you get?“)
Select Case grade
Case 1 To 2
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun!“
Case 3 To 4
MsgBox “Good, here is your movie ticket. Have fun!“
Case >= 4
MsgBox “You should still learn. Sorry! “
Case ““
MsgBox “If you do not enter a grade, you will not get a movie ticket!“
End Select
End Sub
Download now
64
Case 4
MsgBox “Alright. Exceptionally done. Here is your movie ticket! “
Case >= 5
MsgBox
EXCEL “You should still learn. Sorry! “
VBA: INTRODUCTION Program sequence, branch und loops
End Select
End Sub
And here with comma input:
And here with comma input:
Sub Select_Case_Anweisung_II()
grade =InputBox(“Well, what grade did you get?“)
Select Case grade
Case 1 To 2
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have fun!“
Case 3 To 4
MsgBox “Good, here is your movie ticket. Have fun!“
Case >= 4
MsgBox “You should still learn. Sorry! “
Case ““
MsgBox “If you do not enter a grade, you will not get a movie ticket!“
End Select
End Sub
6.2 LOOPS
A loop is a framework which repeats a certain part of the program several times. The loop
part in a procedure is as specified unless another condition is fulfilled. A distinction is made
between pre- and post-tested loops. That is, whether the check condition is in the loop
head or loop foot of the repeat mechanism.
The loop can be terminated prematurely when entering certain state with the exit statement.
¾¾ For...Next statement
¾¾ While…Wend statement
¾¾ Do...Loop statement
In the following example, the counter “i” through 8 is run through. After each run, the
counter increases by the value 1. So i = i + 1.
65
6.2.1 For ... Next – Statement
For...Next - A statement is usually used in combination with a counter that increments after each
loop. The counter
For...Next used here,
- A statement e.g. "I",
is usually used tells
in you how many
combination times
with the loop
a counter should
that go through.
increments The
after each
condition is defined in the head of the loop.
loop. The counter used here, e.g. "I", tells you how many times the loop should go through. The
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
condition is defined in the head of the loop.
In the following example, the counter "i" through 8 is run through. After each run, the counter
increases by the value
In the following 1. Sothe
example, i = counter
i + 1. "i" through 8 is run through. After each run, the counter
increases by the value 1. So i = i + 1.
Sub forward_loop()
For forward_loop()
Sub i = 1 To 8
For i = 1 To 8i
Debug.Print
Next i
Debug.Print i
End Sub
Next i
End Sub
FigureFigure
52: For...Next loop
52: For...Next forward
loop forward
Figure 52: For...Next loop forward
What if the counter should always be increased by the value 2? So, i = i + 2. We’ll do that
with
Whatthe stepcounter
if the statement. Thus
should we indicate
always with which
be increased by the step the 2?
value counter should
So, i = i + 2.beWe'll
increased.
do that with the
step
IfWhatstatement.
if the has
this jump Thus
counter we indicate
should
no sign (plusalwayswith which
be increased
or minus) step the
in front ofbythe
the counter
value
digit, should
2?always
it is be
So, i = increased.
i + 2. or
forward We'll If
dothis
thatjump
positive. with has
the
no sign
step (plus or minus)
statement. Thus wein indicate
front of the
withdigit,
which it step
is always forwardshould
the counter or positive.
be increased. If this jump has
no sign (plus or minus) in front of the digit, it is always forward or positive.
Sub backward_loop_step_2()
For backward_loop_step_2()
Sub i = 2 To 12 Step 2
Debug.Print i Step 2
For i = 2 To 12
Next i
Debug.Print i
End Sub
Next i
End Sub
In the following example we let the counter “i” go through this way 8 times. After each
run, the counter becomes 1 less. So, i = i – 1.
In the following example we let the counter "i" go through this way 8 times. After each run, the
counter becomes 1 less. So, i = i – 1.
Sub backward_loop()
For i = 8 To 1 Step -1
Debug.Print i
Next i
End Sub
Figure 54:54:
Figure For...Next
For...Next loop backward
loop backward
Now a combination with If...Then...Else decisions. The run in the lower example runs with
three
Now asteps backwardwith
combination andIf...Then...Else
is conditionallydecisions.
terminatedTheprematurely. Onceexample
run in the lower the value i iswith
runs less three steps
backward
than 3, exitand is Exit
with conditionally terminated
For before appearingprematurely. Once the
in the immediate area.value
So, ii =isi less
– 3.than 3, exit with Exit
For before appearing in the immediate area. So, i = i – 3.
Sub Combination_If_and_For()
For i = 20 To 1 Step -3
If i<3 Then Exit For
Debug.Print i
Next i 66
End Sub
Debug.Print i Figure 54: For...Next loop backward
Next i
End Sub
Now a combination with If...Then...Else decisions. The run in the lower example runs with three steps
Sub Combination_If_and_For()
backward and is conditionally terminated prematurely. Once the value i is less than 3, exit with Exit
ForFor i = 20
before To 1 Step
appearing in -3
the immediate area. So, i = i – 3.
If i<3 Then Exit For
Debug.Print i
Next i
End Combination_If_and_For()
Sub Sub
For i = 20 To 1 Step -3
If i<3 Then Exit For
Debug.Print i Figure
Figure 55: Combination
55: Combination For...Next
For...Next / If...Then
/ If...Then
Next i
End Sub
Here is a practical example- The cell contents of a table are read out and output. With
the Cells / cell directive, we read the contents of the cell as text. For example, if a cell
Here is a practical example- The cell contents of a table are read out and output. With the Cells / cell
contained “123”,
directive, we readitthe
would be read
contents as text.
of the Buttext.
cell as Figure
if you
For want55:
to Combination
example,read
if aitcell For...Next
as acontained
number, / If...Then
value
"123", /it would be
read as text. But if you want to read it as a number, value
value would have to be written. We will see more of that later. / value would have to be written. We will
see more of that later.
The first
The
Here first value
is avalue in parenthesis
in
practical parenthesis ofofthe
example- The the Cells
cellCells statement
statement
contents indicates
indicates
of a table therow
the
are read rowand
out andoutput.
and thesecond
the second
With value
value indicates
the Cells / cell
the column.
directive, we In our
read example,
the contents "x"
of is incremented
the cell as text.by
For"1" after
example, each
if apass,
cell starting
contained at "1".
"123", The
it second
would be
indicates the column. In our example, “x” is incremented by “1” after each pass, starting at
valueasdoes
read text.not
Butchange, it remains
if you want to readat "1",
it as i.e. the column
a number, value / "A".
valueInwould
addition,
have we arewritten.
to be rebuilding the
We will
“1”. The second
If...Then...Else
see more value
later.does
of thatdecision notOnce
here. change,the itcell
remains at “1”,
to be read i.e. the column
is empty, our loop“A”. In addition,
is terminated.
we are rebuilding the If...Then...Else decision here. Once the cell to be read is empty, our
The first
loop value in parenthesis of the Cells statement indicates the row and the second value indicates
is terminated.
the column. In our example, "x" is incremented by "1" after each pass, starting at "1". The second
Sub Select_Value()
value does not change, it remains at "1", i.e. the column "A". In addition, we are rebuilding the
For x = 1 To 15
If...Then...Else decision here. Once the cell to be read is empty, our loop is terminated.
Debug.Print Cells(x, 1).Text
If Cells(x, 1).Text = "" Then Exit For
Next x
End Select_Value()
Sub Sub
For x = 1 To 15
Debug.Print Cells(x, 1).Text
If Cells(x, 1).Text = "" Then Exit For
Next x
End Sub
Figure 56: Select value from sheet
67
This is about controlling special characters in a string. We assume that the contents of a cell contain
this string. Our example controls until a special character is found.
Our loop starts at "length = 1" and runs maximum number of "Len (cell_content)" through. As soon
as a special character occurs, exit with "Exit Sub".
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
.
.
For length = 1 To Len(cell_content)
Select Case Mid(cell_content, length, 1)
Case "\", "/", ":", "*", ">", "<", "[", "]" 'List of special character
MsgBox "The cell contain special characters." & Chr(10) _
& Mid(cell_content, length, 1) _
& Chr(10) & "Restart after the correction."
Exit Sub
End Select
Next
.
.
I think two examples suffice. We will use For Each..Next statement a bit more later on.
IInthink
the example below,suffice.
two examples all sheets
We (tables,
will use charts, etc.) are statement
For Each..Next output. a bit more later on.
In the example below, all sheets (tables, charts, etc.) are output.
In the example below, all sheets (tables, charts, etc.) are output.
Sub All_Sheets_Name()
Dim objRegister As Object
Sub All_Sheets_Name()
For Each objRegister In ThisWorkbook.Sheets
Dim objRegisterobjRegister.Name
Debug.Print As Object
For Each objRegister
Next objRegister In ThisWorkbook.Sheets
Debug.Print
End Sub objRegister.Name
Next objRegister Figure 57: Names of all sheets
End Sub Figure 57: Names of all sheets
Figure 57: Names of all sheets
Sub Only_Table_Sheets()
Dim wsSheet As Worksheet
SubFor
Only_Table_Sheets()
Each wsSheet In WorkSheets
Dim wsSheet AswsSheet.Name
Debug.Print Worksheet
For Each wsSheet
Next wsSheet In WorkSheets
Debug.Print
End Sub wsSheet.Name
Next wsSheet
End Sub Figure 58: Names of Sheets only
Figure 58: Names of Sheets only
Figure 58: Names of Sheets only
68
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
¾¾ While
Checking is carried out in advance.
6.2.3
¾¾ Until
Do...Loop Statement
6.2.3are
There two Do...Loop Statement
types of von Do…Loop
Checking will be carried
statement:
out afterwards.
There are two types of von Do…Loop statement:
➢ While
Checking is carried out in advance.
In the➢ example
While below we are looking for the term “wheel” with Do ... While ... Loop. In
➢ Until
Checking
column Checking is carrieduntil
“A” it is searched out in advance.
the
will be carried out entry “Wheel” is found. As a result, the address of the
afterwards.
➢ Until
cell is output.
Checking will be carried out afterwards.
In the example below we are looking for the term "wheel" with Do ... While ... Loop. In column "A" it
is searched until the entry "Wheel" is found. As a result, the address of the cell is output.
In the example below we are looking for the term "wheel" with Do ... While ... Loop. In column "A" it
If the contents are incorrect, cell contents are output and if the result is correct, the address
is searched until the entry "Wheel" is found. As a result, the address of the cell is output.
If the contents are incorrect, cell contents are output and if the result is correct, the address of the
of the cell is output from the searched term
cell is output from the searched term.
If the contents are incorrect, cell contents are output and if the result is correct, the address of the
cell is output from the searched term.
Sub DoWhileLoop_Statement_1()
i=1
Sub DoWhileLoop_Statement_1()
Do While Range("A" & i) <> "Wheel”
i=1
Debug.Print Range("A" & i)
Do While Range("A" & i) <> "Wheel”
i=i+1
Debug.Print Range("A" & i)
Loop
i=i+1
Debug.Print Range("A" & i). Value & “Found in cell: “ & Range("A" & i).Address
Loop
End Sub
Debug.Print Range("A" & i). Value & “Found in cell: “ & Range("A" & i).Address
End Sub
69
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
Sub DoUntilLoop_statement_1()
Sub DoUntilLoop_statement_1()
ii =
=1 1
Do
Do Until
Until Range("A"
Range("A" & i) =
& i) = "Rad"
"Rad"
Debug.Print
Debug.Print Range("A" & i)
Range("A" & i)
ii =
= ii +
+11
Loop
Loop
Debug.Print
Debug.Print “Found
“Found in
in cell:
cell: ““ &
& Range("A"
Range("A" &
& i).Address
i).Address
End
End SubSub
Figure
Figure 61:
61: Search
Search with
with Do...Until_1
Do...Until_1
Figure 61: Search with Do...Until_1
This
This example
examplesearches
searchesuntil
untilan
anempty
emptycell
cellisisfound.
found.
This example searches until an empty cell is found.
Sub
Sub DoUntilLoop_statement_2()
DoUntilLoop_statement_2()
ii =
=1 1
Do Until
Do Until Range("A"
Range("A" &
& i) = ""
i) = ""
Debug.Print Range("A" &
Debug.Print Range("A" & i) i)
ii =
= ii +
+11
Loop
Loop
Debug.Print “Next
Debug.Print “Next empty
empty cell
cell is
is in:
in: ““ &
& Range("A"
Range("A" &
& i).Address
i).Address
End
End SubSub
70
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
Sub WhileWend_statement()
i=1
While Range("A" & i) <> ""
Debug.Print Range("A" & i)
i=i+1
Wend
Debug.Print “Next empty cell is in:“ & Range("A" & i).Address
End Sub
The With statement can combine multiple statements for a given object. It brings us two
important benefits:
71
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
1. Less paperwork
6.2.5
2. High With...End With Statement
speed of the module.
The With statement can combine multiple statements for a given object. It brings us two important
benefits:
Between the With and End With statements we first define “where”, then “what” and “how”
1. Lessorpaperwork
to display format. For example, in “cell”, “font” should be displayed in bold.
2. High speed of the module.
In the second example, the column and the row of the active cell are set to the optimal height or
In the second example, the column and the row of the active cell are set to the optimal
width.
height or width.
Sub Examples_With_2() Sub Optimized_Examples_With_2()
ActiveSheet.UsedRange.Select With ActiveSheet.UsedRange
Selection.Rows.AutoFit .Rows.AutoFit
Selection.Columns.AutoFit .Columns.AutoFit
End Sub End With
End Sub
72
.MergeCells = False
End With
End Sub
Such jumps are executed when a condition occurs or enters directly. There are two types:
DDAn UNconditional jump, which continues from the given VBA-code line / jump point,
GoTo or GoSub…Return.
With this statement, our macro continues from the specified line. This line is terminated
with a colon “:”. For example, “Note_2_3:” And this line is then justified to the left in
our listing.
73
Here are some examples to help make it easier to understand.
Sub GoTo_Examplel()
grade = InputBox("Well, which grade did you get?")
grade_1_2:
MsgBox "Great. Here is your movie ticket with popcorn and ice cream. Have fun!"
GoTo Ending:
grade_2_3:
MsgBox "Great. Here is your movie ticket. Have fun!"
GoTo Ending:
garde_4_5:
MsgBox "You should still learn. Sorry!"
GoTo Ending:
grade_6:
MsgBox "You need tutoring!"
Ending:
End Sub
It is very similar to the GoTo statement. The difference is that the Return statement below
the GoSub statement returns to where it left off.
I describe it here with a funny example, let’s say you have a dog and you two play in a
meadow with a ball. You throw the ball to the left, your dog runs over different hills, picks
up the ball and brings it back. Now you throw it to the right and the dog runs through
the trees and brings the ball back. If you or your dog are tired then you go home.
74
I describe it here with a funny example, let's say you have a dog and you two play in a meadow with
a ball. You throw the ball to the left, your dog runs over different hills, picks up the ball and brings it
back. Now you throw it to the right and the dog runs through the trees and brings the ball back. If
you or your dog are tired then you go home. ☺
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
Sub Example_GoSub()
Range("A1").Select
i=0
repeat:
CellValue = ActiveCell.Offset(i, 0).Value
ActiveCell.Offset(i + 1, 0).Select
If CellValue = "" Then Exit Sub
Select Case CellValue
Case 1, 2
GoSub intValue
Case 3
GoSub intValue_3
Case "Gear"
GoSub Text
End Select
GoTo repeat
intValue:
Factor = 0.5
Result = CellValue * Factor
Debug.Print Result
Return
'
intValue_3:
Factor_3 = 0.7
Result = CellValue * Factor_3
Debug.Print Result
Return
'
Text:
Add_Text = "Additional Text"
Result = CellValue & vbLf & Add_Text
Debug.Print Result
Return
'
If ActiveCell.Offset(i, 0).Value = "" Then
Exit Sub
Else
GoTo repeat
End If
End Sub
Now what is going on here? There are entries in column "A" in the Excel sheet. Depending on the
"Content" entry, it is decided which GoSub statement should be executed. If it is"Content = 1,2,4,5"
Now what is going on here? There are entries in column “A” in the Excel sheet. Depending
or "6", then "GoSub Number" will be executed. If it is "content = 3", then "GoSub number_3" will be
on the “Content”
executed, entry,
if "content it isthen
= rt", decided which
"GoSub Text"GoSub statement should be executed. If it
is executed.
is”Content = 1,2,4,5” or “6”, then “GoSub Number” will be executed. If it is “content = 3”,
then “GoSub
Here's number_3”
the same examplewill
withbeIf-Then
executed, if “content = rt”, then “GoSub Text” is executed.
75
EXCEL VBA: INTRODUCTION Program sequence, branch und loops
Sub Example_GoSub_If()
Range("A1").Select
i=0
repeat:
CellValue = ActiveCell.Offset(i, 0).Value
ActiveCell.Offset(i + 1, 0).Select
If CellValue = "" Then Exit Sub
If CellValue = 1 Or CellValue = 2 Then GoSub Zahl
If CellValue = 3 Then GoSub Zahl_3
If CellValue = "rt" Then GoSub Text
GoTo repeat
intValue:
Factor_1 = 0.5
Result = CellValue * Faktor_1
Debug.Print Result
Return
'
intValue_3:
Factor_2 = 0.7
Result = CellValue * Faktor_2
Debug.Print Result
Return
'
Text:
Add_Text = "Additional Text"
Result = CellValue & vbLf & Add_Text
Debug.Print Result
Return
'
If ActiveCell.Offset(i, 0).Value = "" Then
Exit Sub
Else
GoTo repeat
End If
End Sub
76
EXCEL VBA: INTRODUCTION Communication with Excel
Communication with Excel is a mixture of these two definitions. Because we sit opposite
of Excel, we tell the Excel by menu selection what it should do and it follows or it outputs
a message window.
77
EXCEL VBA: INTRODUCTION Communication with Excel
Using VBA instructions, we can display such messages or masks in different ways and make
them appear on the desktop:
As long as a message window is displayed on the screen, you can’t work in the Excel file or
in the VBE code. The message window must be closed first in order to carry on.
78
background to distinguish which key is pressed. The selected key then returns a value of type Integer.
on the
The screen.isMsgBox
message waitinghas
for at least one
a button "OK" button
displayed insideto
it confirm. Each button has a return value in the
to be clicked.
background to distinguish which key is pressed. The selected key then returns a value of type Integer.
message
The syntax of is
thewaiting
MsgBox forfunction
a buttonwith
displayed inside it to be clicked.
its arguments:
MsgBox
EXCEL VBA: (prompt [, buttons] [, title])
INTRODUCTION Communication with Excel
The syntax of the MsgBox function with its arguments:
MsgBox
As long as(prompt [, buttons]
a message window[,istitle])
displayed on the screen, you can’t work in the Excel file or in the
VBE code. The message window must be closed first in order to carry on.
As long as a message window is displayed on the screen, you can’t work in the Excel file or in the
VBE code. The message window must be closed first in order to carry on.
Sub MsgBox_simly()
MsgBox "I learn VBA."
Sub Sub
End MsgBox_simly()
MsgBox "I learn VBA."
End Sub
Figure 68: Figure
Example68: MsgBox_1
Example MsgBox_1
If you want to display additional buttons other than OK, such as Cancel, either with a
constant or the value button then these buttons must be programmed accordingly. In the
same section as the “OK” button you will also find “Cancel”. In programming, either the
If ... Then ... Else or the Select ... Case statement is used. Both variants are displayed below.
79
EXCEL VBA: INTRODUCTION Communication with Excel
80
EXCEL VBA: INTRODUCTION Communication with Excel
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Here are two examples. In the first one, we let the OK and Cancel buttons appear in
the message window with “Buttons: = vbOKCancel”. Thereafter, the follow-up action is
displayed after the determined return value with the “Select Case” message.
In the second example, we also use “Buttons: = 1” to display OK and Cancel buttons in
the message window. The return value is then evaluated with the If..Then decision and a
corresponding message is displayed.
81
vbYes 6 Yes
vbNo
Here are two examples. In the first one,7we let the
No OK and Cancel buttons appear in the message
window with "Buttons: = vbOKCancel".
Table 4: Return values of a button Thereafter, the follow-up action is displayed after the
determined return value with the "Select Case" message.
EXCEL VBA: INTRODUCTION Communication with Excel
Here
In theare two examples.
second example, weIn also
the first one, we let
use "Buttons: thetoOK
= 1" and Cancel
display OK andbuttons appear in
Cancel buttons in the message
the message
window with "Buttons: = vbOKCancel". Thereafter, the follow-up action is displayed
window. The return value is then evaluated with the If..Then decision and a corresponding messageafter the
determined
is displayed.return value with the "Select Case" message.
In theMsgBox_Button_Select()
Sub second example, we also use "Buttons: = 1" to display OK and Cancel buttons in the message
window. The return
Dim intAnswer value is then evaluated with the If..Then decision and a corresponding message
As Integer
is displayed.
intAnswer = MsgBox("I learn VBA.", _
Sub MsgBox_Button_Select()
Buttons:=vbOKCancel, _
Dim intAnswer As Integer
Title:="My Message")
intAnswer
Select = MsgBox("I learn VBA.", _
Case intAnswer
Case vbOK Buttons:=vbOKCancel, _
MsgBox "You Title:="My Message")
have selected OK."
Case Else
Select Case
MsgBox intAnswer
"You have selected Cancel."
Case
End vbOK
Select
MsgBox "You have selected OK."
Case
End SubElse
MsgBox "You have selected Cancel."
End Select
Sub MsgBox_Button_If()
End
DimSub
intAnswer As Integer
intAnswer
If intAnswer ==MsgBox("I
1 Then learn VBA.", _
Buttons:=1, _
MsgBox "You have selected OK."
Else Title:="My Message")
Figure 73: Result from Select Case / If...Then...Else
MsgBox "You have selected Cancel."
If
EndintAnswer
If = 1 Then
MsgBox
End Sub "You have selected OK." Figure 73: Result from Select Case / If...Then...Else
Else Figure 73: Result from Select Case / If...Then...Else
MsgBox "You have selected Cancel."
End If
End Sub
82
7.2 Break up or concatenate multiline text lines
The width of the message window is a maximum of 128 characters. After that it is automatically
wrapped. This can sometimes seem ugly and confusing. It can be formatted better by using the ASCII
code VBA:
EXCEL and system-internal
INTRODUCTION constants for tab and breaks. Communication with Excel
Table
Table 5: Formatting
5: Formatting a text
a text in in the message
the message window window
Sub Break_up_or_concatenate()
Dim strFirstName As String
strFirstName = "Harun,"
'Result in MsgBox
MsgBox "Hello " & strFirstName & vbLf & vbLf & _
"Congratulations to your first child." & Chr(10) & _
Chr(10) & vbCr & _
Date & vbTab & Time
83
EXCEL VBA: INTRODUCTION Communication with Excel
vbExclamation
vbInformation Exclamation mark Information mark
vbInformation
vbSystemModal Information mark
Dialog box remains in the foreground
vbSystemModal Dialog box remains in the foreground
Table 6: Symbols in Message window
Table 6: Symbols in Message window
Sub MsgBox_Symbol()
MsgBox "That’s a stop mark.", vbCritical
MsgBox "That’s a question mark.", vbQuestion
MsgBox "That’s an exclamation mark.", vbExclamation
MsgBox "That’s an information mark.", vbInformation
End Sub
Sub MsgBox_SystemModal()
MsgBox "I stay in sight until you read me." & vbLf & _
"If you also change your application, I’m still there!", _
vbOKOnly Or vbSystemModal, "I have to read that!"
End Sub
84
EXCEL VBA: INTRODUCTION Communication with Excel
The constant vbSystemModal causes the message in the foreground to freeze if other
programs are also used.
• to enter something
• to click on one of two (OK and Cancel) buttons.
The syntax of the InputBox function with its arguments is in the help text, as follows:
InputBox (prompt [, title] [, default])
To program the two buttons, either the If ... Then ... Else or the Select ... Case statement
is used. The decision is determined according to the constant or the value of the individual
buttons.
In the next example, the user is prompted to enter his name. With the “Title” value, the
name of the window is entered here “enter name”, and with the default value a specific
name is entered here “Harun Kaplan”. This name is already displayed in the input field.
85
To program the two buttons, either the If ... Then ... Else or the Select ... Case statement is used.
To decision
The programisthe two buttons,
determined either to
according the If constant
the ... Then ...
or Else or theofSelect
the value ... Case buttons.
the individual statement is used.
The decision is determined according to the constant or the value of the individual buttons.
In theVBA:
EXCEL next example, the user is prompted to enter his name. With
INTRODUCTION the "Title" value,
Communication the name of the
with Excel
In the next
window example,
is entered herethe user name",
"enter is prompted
and to
withenter
the his name.
default Withathe
value "Title"name
specific value,isthe name here
entered of the
window is entered here "enter name", and with the default
"Harun Kaplan". This name is already displayed in the input field. value a specific name is entered here
"Harun Kaplan". This name is already displayed in the input field.
Sub Example_InputOutput()
Substrmy_Name
Dim Example_InputOutput()
As String
Dim strmy_Name As String
strmy_Name = InputBox _
strmy_Name
("Please = InputBox
enter your _ _
name: ",
("Please enter your name:your
Title:="Enter ", _ name", _
Title:="Enter your
Default:="Harun name", _
Kaplan")
Default:="Harun Kaplan")
MsgBox strmy_Name
MsgBox
End Sub strmy_Name
End Sub
86
EXCEL VBA: INTRODUCTION Communication with Excel
Sub Practical_Example_2()
repeat:
intInput = InputBox("Please Enter your number!", _
Title:="Input number", _
Default:=5)
'Control selected button
Select Case intInput
Case ""
Exit Sub
End Select
'Control input, if input number or text
If IsNumeric(intInput) = True Then
If intInput < 5 Then 'by value control which number
Title = "The value is less than 5"
a=2
b=3
ElseIf intInput >= 5 And intInput <= 10 Then
Title = "The value is between 5 and 10"
a=4
b=5
ElseIf intInput >= 10 And intInput <= 15 Then
Title = "The value is between 10 and 15"
a=6
b=7
End If
Else
MsgBox ("Please enter your value!")
GoSub repeat 'If input no number, continue with by “repeat”
End If
Result = a * b
strOutput = MsgBox(("First value = " & a & vbLf & _
"second value = " & b & vbLf & _
"Result = " & Result), , Title)
End Sub
87
EXCEL VBA: INTRODUCTION Bibliography
BIBLIOGRAPHY
88