Excel Vba Introduction 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 88
At a glance
Powered by AI
The key takeaways are that the book introduces Excel VBA programming concepts like the editor environment, macros, variables, operators, errors, program flow, and communicating with Excel.

The main topics covered in the book include the VBA editor environment, recording macros, variables, operators, errors, program flow with decisions and loops, and communicating with Excel using messages and input boxes.

The book is organized into four parts that cover an introduction to VBA, working with Excel elements, functions and data, and toolbar controls.



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

1 Visual Basic for Application – VBA 8

2 Developer Environment 9
2.1 VBA-Editor Environment 10

3 “Learning by recording” Record of macro 18


3.1 Structure of a procedure 18
3.2 Delete, export or import of Macros / Procedure 24
3.3 Start a macro 25

4 Script concept by VBA 30


4.1 Procedure, Module, VBA-Code 30
4.2 Variable, constant and date type 36
4.3 Arithmetic-, comparison- und logical Operators 50

Discover our eBooks


on Leadership Skills
and hundreds more

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

6 Program sequence, branch und loops 59


6.1 Decision structure, If query, Branches and returns 59
6.2 Loops 65
6.3 Branch statement 73

7 Communication with Excel 77


7.1 Message window 78
7.2 Break up or concatenate multiline text lines 82
7.3 Symbol in Message window 83
7.4 Input window 85

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.

These include users who:

• want to work extensively with Excel.


• have no programming knowledge and want to learn VBA programming.
• have already started programming in VBA or other languages.
• want to expand their VBA skills.

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.

This book series consists of four parts:

DDExcel VBA - Introduction


DDExcel VBA – Working with Excel Elements
DDExcel VBA – Working with Excel Functions & Data
DDExcel VBA – Working with ToolBar Controls

Harun Kaplan

6
EXCEL VBA: INTRODUCTION Introduction

For my Family:
Tülay
Yasin, Sueda, Melik

7
EXCEL VBA: INTRODUCTION Visual Basic for Application – VBA

1 VISUAL BASIC FOR


APPLICATION – VBA
I remember how happy I was when my first programs with GWBasic and Turbo Pascal
went through without any errors.

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.

How do I get there?

There are two ways to access the developer tools:

• Using the key combination “Alt+F11”


• Through the menu “”Developer” as show below:

Figure 1: Starting of developer

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 “.

Figure 2: Starting of VBA-Editor

9
EXCEL VBA: INTRODUCTION Developer Environment

2.1 VBA-EDITOR ENVIRONMENT


The Microsoft Visual Basic window can have different surfaces at the same time which can
be faded in and out as desired.

Figure 3: VBA-Surfaces

10
EXCEL VBA: INTRODUCTION Developer Environment

Names of the window areas:

1. VBA-Editor
2. Project Editor
3. Properties
4. Watches
5. Immediate
6. Locals

Now we can look at them in detail.

2.1.1 THE VBA - EDITOR

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:

• Automatic insertion of blank lines,


• Color representation of fonts (Comment | Command | Function | Methods),
• Line break with “space” possible.

11
EXCEL VBA: INTRODUCTION Developer Environment

Figure 4: Change between Procedure View & Full Module View

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”.

When the development environment starts, it opens by default. However, if it should be


missing, you can use the menu “View | Project Explorer “or use the keyboard shortcut
“Ctrl + R”.

12
EXCEL VBA: INTRODUCTION Developer Environment

Figure 5: Project

2.1.3 PROPERTIES WINDOW

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

• Menu “View | Properties Window “


• Function key “F4”

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

Figure 7: Without group

Figure 6: With group

2.1.5 WATCH WINDOW

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

Figure 8: Starting of watch window

Next we add an expression to the Watch Window:


Via menu “Debug | Add watch “. Once a variable in the “Add Watch” is confirmed, the
watch window appears:

Discover our eBooks on


Communication Skills
and hundreds more

Download now

15
EXCEL VBA: INTRODUCTION Developer Environment

Figure 9: Insert an expression in add watch

Or we mark the item to be monitored and drag it with the mouse into the Watch Window,
which is shown in Figure 10.

Figure 10: Result in add Watch Window

2.1.6 IMMEDIATE

The Immediate Window has the following functions:

• Execute directly entered VBA statements


• Display determined values of the variables

The variables start in the VBA code with the Debug.Print”.

You can open this window via menu “View | Immediate window” or with the key
combination “Ctrl + g”.

16
• Display determined values of the variables

The variables start in the VBA code with the "Debug.Print".


EXCEL VBA: INTRODUCTION Developer Environment
You can open this window via menu "View | Immediate window" or with the key combination
"Ctrl + g".

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

Figure 11: Result in Immediate window

Figure 11: Result in Immediate window


2.1.7 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.
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.

The local window is opened via menu View | Locals window “.

Figure 12: Local window with elements to be monitored

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.

The recorded macros do not allow dynamic actions.

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

There are two types of records:

• 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.

3.1 STRUCTURE OF A PROCEDURE


A procedure is nothing more than a macro that starts with Sub and ends with End Sub.
The name of a procedure must not exceed 255 characters and ends with empty parentheses.

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.

Figure 13: Structure of a procedure

Now we can record our first macro.

3.1.1 THE RECORDING OF MACRO

The macro recording is made via the menu command “Developer | Record Macro “.
Alternatively, the switch on the VISUAL BASIC toolbar can be used.

Figure 14: Starting of recording macro

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:

• Enter the macro name


○○ Max 255 characters long
○○ Name must begin with a letter
○○ “Umlaut” (ä,ö,ü) in the name is permitted
○○ Spaces and Hyphens are not allowed
• Define key combination for starting the macro (start alternative)
○○ By entering the letter “a” in the example above, the shift-key was held down.
• Enter the macro description
○○ Information about the function of the macro
• Select the macro mapping in the “Store macro in” drop-down-list.
○○ If a macro is to be assigned to the work in which it was recorded. “This
workbook” is selected here. The personal macro workbook selection makes
the macro widely available in all workbooks.

Figure 15: Recording Macro and Listing.

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.

3.1.2 RECORDING EXAMPLE

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".

Figure 16: “Format Cells”- window


Figure 16: "Format Cells"- window

Our record looks like this:


Our record looks like this:

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

Now we adapt our record regarding clarity:

Sub Macro_recording()
Range("A1:C4").Select
Selection.NumberFormat = "0.000"
'Tap font
With Selection.Font
.FontStyle = "Fett"
.Size = 16
End With
End Sub

3.1.3 CHANGE AN ABSOLUTE RECORDING TO A RELATIVE RECORDING

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

Now, hire is the Relative Recording:


Sub Makro_Recording()
ActiveCell.Range("A1:C3").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

3.1.4 ABSOLUTE OR RELATIVE RECORDING

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.

Figure 17: Starting of “Use Relative References“

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

Figure 18: Relative recording


Figure 18: Relative recording

23
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro

Figure 18: Relative recording

3.2 DELETE, EXPORT OR IMPORT OF MACROS / PROCEDURE


A recorded macro is opened via the menu command “Developer | Macros “. Click on the
“Delete” button in the dialog box to delete a selected macro.

Figure 19: Delete of a macro

3.2.1 EXPORT (REMOVE) AND IMPORT OF MODULE

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

Figure 20: Exporting or Deleting of Macros

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”.

3.3 START A MACRO


Macros can be opened in several different ways:

• From the editor


• By keyboard shortcut
• By assignment to a key or to an object
• After a certain time
• Function keys
• Through the call statement in procedure and
• Start with your own menu programming.

25
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro

3.3.1 STARTING BY EDITOR

In VBA editor, position the cursor somewhere in procedure, then

• by pressing the F5 key or by pressing F8 for a step by step sequence


• Click the blue arrow in the toolbar or,
• Via the menu command „Execute | Sub | User Form“.

Figure 21: Starting from Editor

3.3.2 SHORTCUT: CTRL + SHIFT + {CHARACTER}

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.

Subsequent assignment of a key combination looks like this:

Figure 22: Start a macro by shortcut

26
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro

3.3.3 ASSIGN MACRO TO A BUTTON

Such buttons can be created from a toolbar of the form, the Autoforms, or the controls
Toolbox.

To assign a macro, proceed as follows:

• Mark the button


• Right-Click on the “Assign Macro” window
• Select macro
• Confirm with OK-button

Discover our eBooks on


Time Management Skills
and hundreds more

Download now

27
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro

3.3.4 ASSIGN MACRO TO AN OBJECT

Figure 23: Assign macro to an object

3.3.5 STARTING A MACRO IN WORKBOOK_OPEN()-EVENT

“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.

Figure 24: Instruction in workbook_open()-Event

¾¾ Syntax for starting at a specific time:


Applicatio.OnTime Timevalue (“Hour: Minute: Second”), “Macro to invoke”

¾¾ Syntax for start via function key:


Applicatio.OnKey “{Function key},”recorded macro”

¾¾ Syntax for the start via call statement:


Call <procedure name>

28
EXCEL VBA: INTRODUCTION “Learning by recording” Record of macro

3.3.6 STARTING A MACRO FROM AN EXTERNAL EXCEL FILE

The “Application.Run” statement will open a macro or function from an external Excel file.

In our example, “MacroName” is executed from the Excel file “Filename”.

Application.Run “’” & Filename & “’!MacroName”

3.3.7 THE SECURITY

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.

Figure 25: Security settings

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

4 SCRIPT CONCEPT BY VBA


Before delving into the world of VBA language elements, I would like to explain some
prerequisites for VBA programming.

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:

• Automation of standard tasks.


• Function extension by “own” functions.
• Programming a user interface (UserForm) as Excel application tools.

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:

• Excel application as an Application


• Workbooks as a Workbook
• Excel sheet as a Sheet
• Individual areas as a Range
• Cells itself as Cells / Range
• Properties of cells, for example font color as FontColor.

4.1 PROCEDURE, MODULE, VBA-CODE


We have already seen the chapter 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 refer to it as the “head and foot” of the VBA program.

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

4.1.2 UPPER- AND LOWER-CASE

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.

4.1.3 ARGUMENTS IN FUNCTIONS UND METHODS

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:

¾¾ Range(“D1”).Value = WorksheetFunction.CountIf(Range(“C:C”), “Stuttgart”)

4.1.4 COMMENTARY LINE

Sections of text starting with an apostrophe are marked as comments by the VBA editor.
They are not executed.

You can add your comments as a line or at the end of a statement.

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".

Figure 27: Annotate a VBA-Code


Figure 27: Annotate a VBA-Code
Sub Example_Annotate_with_Apostrophe()
'With Indenting
'Stand: 16.06.11, Ka
For x = 1 To 5 'This loop run 5x
If name = "Harun" Then 'Control to
Range("A" & x).Value = name & "_" & x
Else
Range("B" & x).Value = name & "_" & x
End If
Next x
End Sub

4.1.5 LIST PROPERTIES AND METHOD – INTELLISENSE

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.

IntelliSense is a VBA-supplied tool for automatically completing commands in source code.

If it does not work, “Ctrl + j” or “Ctrl + Spacebar” can help.

Figure 28: Example IntelliSense

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.

Figure 29: IntelliSense by a constant

4.1.6 QUICK INFO

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:

Figure 30: Quick info-Example of „Offset“

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:

Figure 31: Quick info-Examples of MsgBox with arguments

34
EXCEL VBA: INTRODUCTION Script concept by VBA

In our second example, we used the MsgBox function.

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.

Figure 32: Show a variable as Quick info

4.1.7 GAP OR CONCATENATE OF A MULTI-LINE IN VBA-SYNTAX

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.

¾¾ A line break is realized with a combination of a space and an underscore!

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.

The following example illustrates both variants.

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

The following example illustrates both variants.

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

4.2 VARIABLE, CONSTANT AND DATE TYPE


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 execution and, if necessary, used later or taken over by another (sub) procedure.

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.

Here is an explanation of what a data type is:


We assume that the term “people” should be our data. People are all “men, women and
children”. If we dimension them individually, it would look like the example shown below.
All “men, women and children” belong to the species “human”.

¾¾ Dim men, woman, child As human

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:

Dim intNumber1, intNumber2 As Integer


Dim intNumber3, intNumber4 As Long

VBA knows the following data types (variable types):

Data type Prefix Descripting

An array is a data structure that contains several variables


Array arr
of the same type.

Holds unsigned 8-bit integers that range in value from 0


Byte byt
through 255.

37
EXCEL VBA: INTRODUCTION Script concept by VBA

Data type Prefix Descripting

Boolen bln Holds values that can be only True or False.

Fixed-point number with 15 digits in front and 4 digits after


Currency cur
the decimal rounded.

Date dat Date and time.

Floating point number with 16 digits precision, positive and


Double dbl
negative values.

Integer int Numbers with values ± 2.147.483.647.

Long lng Numbers with values ± 9.223.372.036.854.775.808.

Floating point number with 8 digits precision, positive and


Single sng
negative values.

Holds sequences of unsigned 16-bit code points that range


String str
in value from 0 through 65535.

Object obj Holds addresses that refer to objects.

Variant var Numbers values or strings.

Table 1: Abbreviation of Date-type with descripting

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

Figure 33: Example


Figure Date-type_1
33: Example Date-type_1

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

Figure 34: Example Date-type_2


Figure 34: Example Date-type_2

4.2.2 ABBREVIATION OF PREFIX IN VBA-CODE

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.

4.2.3 THE SCOPE OF VARIABLES

A variable can be addressed within the following locations:

¾¾ only in one procedure / function (local; procedure-level)


¾¾ in a module (module-level)
¾¾ in all modules (project-level)

40
EXCEL VBA: INTRODUCTION Script concept by VBA

4.2.4 VALIDITY WITHIN A PROCEDURE

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”.

Figure 35: Validity within a procedure with output

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.

4.2.5 VALIDITY WITHIN A MODULE

Validity within a module means that a variable is valid in all procedures. This variable is
declared outside the procedures.

Figure 36: Validity within a module, therefore in all 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:

Dim intValue3 As String 'With Dim declared


Private Sub Validity_Range_3()
intValue3= 231
Validity_Range_4 Can be written here with or without Call Validity_Range_4
End Sub

Private Sub Validity_Range_4()


MsgBox intValue3
Call Validity_Range_5
End Sub

Private Sub Validity_Range_5()


MsgBox intValue3 + 29
End Sub

Discover our eBooks


on Leadership Skills
and hundreds more

Download now

42
EXCEL VBA: INTRODUCTION Script concept by VBA

4.2.6 PASSING VARIABLES TO A PROCEDURE AND TO A FUNCTION

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”.

Here are the examples:

Figure 37: Passing variable to a sub-procedure

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”.

Figure 38: Passing variable to a function

4.2.7 VALIDITY WITHIN ALL PROCEDURES OF A WORKBOOK

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”.

We get the value “32” everywhere as a result.

Figure 39: Validity of a variable in workbook

4.2.8 STATIC VARIABLE

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”.

Also, start this “y-value” at “0”

• a runtime error occurs


• the “Static” procedure is aborted
• Excel is finished

Figure 40: Functionality of a Static-statement

4.2.9 SET VARIABLE OF OBJECT

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.

Such Excel objects are:

• Cells / Ranges of a table (Range);


• All diagrams (Charts), tables (Worksheets);
• All folders (Workbooks);
• Forms.

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

Here is the example with the set statement:


Here is the example with the set statement:
Here is the example with the set statement:
Sub Example_with_Set()
Dim
Sub Cell1 As Range
Example_with_Set()
Dim
Dim Cell1As
Cell2 AsRange
Range
'Dim Cell2 As Range
Set
' Cell1 = Worksheets("Sheet1").Range("A1")
Set
Set Cell2
Cell1 ==Worksheets("Sheet2").Range("A1")
Worksheets("Sheet1").Range("A1")
'Set Cell2 = Worksheets("Sheet2").Range("A1")
Cell1
' = 1923
Cell2 = Cell1 * 2.5
Cell1 = 1923
End Sub
Cell2 = Cell1 * 2.5
End Sub

Figure 41: Result Set

Figure 41: Result Set


Figure 41: Result Set

46
EXCEL VBA: INTRODUCTION Script concept by VBA

4.2.10 USER-DEFINED DATE TYPE

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

Private Type Autor


intNumber As Integer
strFirstName As String * 15
strName As String * 20
strTitle As String * 10
blnGender As Boolean
strPostCode As String * 5
strStreat As String * 20
strPlace As String * 20
datBirthday As Date
strPhone() As String
strTelefax(1 To 2) As String
sinSalary As Single
End Type

Private Type Book


strTitle As String * 25
strType As String * 5
End Type

4.2.11 STATEMENT CONST – UNCHANGED VALUE -

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

Figure 42:Result of Constants_1


Figure 42:Result of Constants_1

Figure 42:Result of Constants_1


4.2.12 VBA CONSTANTS

There are also many (system) integrated constants in VBA. They begin with the prefix

DDvb Visual Basic


DDxl Excel.

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

vbRed Red color vbYellow Yellow color

VbGreen Green colorvbBlue Blue color


vbYellow Yellow color
vbMagenta Magenta color
vbBlue Blue color
vbCyan Cyan-blue color
vbMagenta Magenta color
vbWhite White color
vbCyan Cyan-blue 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

Discover our eBooks on


Communication Skills
and hundreds more

Download now

49
EXCEL VBA: INTRODUCTION Script concept by VBA

4.3 ARITHMETIC-, COMPARISON- UND LOGICAL OPERATORS


The values for the arithmetic process can come from different data sources. For instance:

• as a variable in the program


• from Excel sheet
• as an intermediate value from a calculation
4.3 • Arithmetic-, comparison- und logical Operators
a result from a formula
The values for the arithmetic process can come from different data sources. For instance:
• as a variable in the program
• from Excel sheet
• as an intermediate value from a calculation
• a result from a formula
4.3.1 ARITHMETIC OPERATORS
4.3.1
These serve to Arithmetic Operators
carry out calculations. My first example will be with the values from the
These serve to carry out calculations. My first example will be with the values from the examples
examples mentioned above.
mentioned above.

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

Debug.Print "From Variable: " & Chr(10) & x + y


Debug.Print "From Excel-Sheet: " & Chr(10) & a + b
Debug.Print "From Formula: " & Chr(10) & z
End Sub

Figure 43: Example arithmetic operators


Figure 43: Example arithmetic operators
The following arithmetic operators are used in the VBA code:

* 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

The following arithmetic operators are used in the VBA code:

* 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

Other orders may need to be specified by parentheses:


(12 + 3) * 5 = 75

4.3.2 COMPARISON OPERATORS

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

Well, here is an example of IS or LIKE:

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.

Well, here is an example of IS or LIKE:


Sub IS_Compare()
Dim Object1, NewObject, Object2, Object3, Object4, Test1
•Set
IS NewObject
is used to compare two different
= Object1 variables
' Object with references to objects.
allocation
Set Object2 = Object1
Sub IS_Compare()
Set Object4 = Object3
Dim Object1, NewObject, Object2, Object3, Object4, Test1
Test1 = NewObject Is Object2 ' result true.
Set NewObject = Object1 ' Object allocation
Test1
Set = Object4
Object2 Is Object2
= Object1 ' result false.
'Set
Accepted: Object1
Object4 = Object3 <> Object3
Test1 ==NewObject
Test1 Object1 IsIsObject4
Object2 '' result
result true.
False.
End Sub
Test1 = Object4 Is Object2 ' result false.
' Accepted: Object1 <> Object3
IfTest1
both=Object1
Object1 and Object2 refer
Is Object4 to False.
' result the same object, the result is TRUE, otherwise the result is
FALSE.
If
End both
SubObject1 and Object2 refer to the same object, the result is TRUE, otherwise the
result is FALSE.
• LIKE
If both is used to
Object1 compare
and Object2a refer
stringtowith
the asame
pattern.
object, the result is TRUE, otherwise the result is
FALSE.
Sub like_Compare()
• LIKE is used to compare a string with a pattern.
•Dim
LIKE is used
Test1 As to compare a string with a pattern.
String
Test1 = "aBBBa" Like "a*a" 'First and last letter are true
Sub like_Compare()
Test1 = "F" Like "[A-Z]" 'True. The “F” is content of A-Z
Dim Test1
Test1 As String
= "a2a" Like "a#a" 'True. First and last letter is “a”
Test1 = "aBBBa"
Test1 = "aM5b" Like Like "a*a" 'First and last
"a[L-P]#[!c-e]" letter
'True. are
First true is “a” and last letter is content to e.
letter
Test1 = "F" Like "[A-Z]" 'True. The “F”
Test1 = "BAT123khg" Like "B?T*" 'True. First and thirdis content of A-Zletter are true.
Test1 = "a2a" Like "a#a" 'True. First and
Test1 = "CAT123khg" Like "B?T*" 'False. First and last last letter is “a”
letter do not apply.
Test1 = "aM5b" Like "a[L-P]#[!c-e]" 'True. First letter is “a” and last letter is content to e.
End Sub
Test1 = "BAT123khg" Like "B?T*" 'True. First and third letter are true.
Test1 = "CAT123khg" Like "B?T*" 'False. First and last letter do not apply.
End Sub

4.3.3 LOGICAL OPERATORS

In addition to mathematical and comparison operators, there are logical operators. The
result is output with a Boolean expression.

The statement in VBA syntax is:

Result = [Comparison_1] Operator [Comparison_2]

There are six logical operators:

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 is used to perform a logical exclusion between two expressions.
Eqv is used to determine a logical equivalence between expressions.
Imp serves to perform a logical implication between two expressions.

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.

Figure 44: Option Explicit

5.1 Errors examples


5.1 ERRORS EXAMPLES

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

Figure 46: incorrect / missing Definition

Figure 47: incorrect / missing input or output

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.

5.2 HANDLING ERRORS


The error messages can be suppressed with the On Error Resume Next instruction. From
the “On Error Resume Next” line, all error messages are suppressed. It is valid in the whole
procedure. It can’t be recognized by fatal errors.

If necessary, On Error Resume Next can be deactivated withOn Error Goto 0.


On Error Goto VBA-String line redirects the VBA code flow to the line.

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

But we can also redirect the process to a message in case of an error:

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

Figure 48: Redirect of error


Figure 48: Redirect of error

5.3 TOOLBAR DEBUG


Debugging is an important part of VBA. It is used primarily for tracking variable content.
Or in case of an error message, VBA suggests starting the debugger.

Figure 49: Toolbar Debug

Now let’s have a look at the individual icons with their tasks.

56
EXCEL VBA: INTRODUCTION Errors in VBA

5.3.1 STEP INTO

The macro can be executed in single step mode also named “Step by Step“.

Actions of the function keys:

• executed step by step with the F8 key,


• executed with the key F5 to the end,
• aborted with the key combination Ctrl + Shift + F8,
• repeated with the key combination Ctrl + F8,
• Position the yellow arrow on any line with the mouse and continue from there
with the F8 or F5 keys.

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.

In our example it looks like this

Figure 50: Current line in VBA-Editor

5.3.2 CURRENT LINE

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.

5.3.3 TOGGLE BREAKPOINT

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

The breakpoints can:

• Be inserted or removed on the desired line with the F9 key.


• Be inserted or removed on the desired line with a mouse click.
• remove all breakpoints with the key combination Ctrl + Shift + F9.
• Be carried out automatically with the F5 key until the next breakpoint.

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

Figure 51: Example bookmarks

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 DECISION STRUCTURE, IF QUERY, BRANCHES AND RETURNS


Branches and jump labels are used to change the program sequence due to certain conditions
or to jump to a designated place and continue from there.
6 Program sequence, branch und loops
An important VBA code part is the control of the program sequences depending on the situation. The
Aprocedure
query works after
should reactandifferently
operationdepending
with the on
following program
the determined section.
value. If the
It's like condition
a traffic light. Ifisgreen
true, this section
then drive willthen
and if red be processed and if then
stop, or if yellow not, yield.
another section will be processed.
Or in other words: as long as nothing changes, this action is carried out; as soon as something
In VBA there
changes, are the
the action following
is also statements to realize such queries:
changes.

6.1 Decision structure, If query, Branches and returns


• IIF function
Branches and jump labels are used to change the program sequence due to certain conditions or to
jump •
to Only useful for
a designated a query
place / decision.
and continue from there.
• If-Then-Else statement; completed with End If
A query works after an operation with the following program section. If the condition is true, this
• will
section Forbeclarity, this variant
processed is for
and if not, max. section
another three queries / decisions makes sense.
will be processed.
• Select Case statement; completed with End Select.
In VBA there are the following statements to realize such queries:
• IIF function
• Only useful for a query / decision.
• If-Then-Else statement; completed with End If
• For clarity, this variant is for max. three queries / decisions makes sense.
Select
• IIF
6.1.1 Case statement; completed with End Select.
FUNCTION

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_with_Iif()


Note = InputBox("Well, what grade did you get?")
MsgBox IIf(Note > 2 And Note < 3, " Good, here is your movie ticket. Have fun!", "Sorry.")
End Sub

6.1.2 If … Then … Else statement


A commonly used decision is if ... Then ... Else. We know this process from Excel as an if-then
function. How does it work? They work like a vegetable and fruit shop. You get a new delivery. You
should then put the goods on the right shelf. If you have a box of apples in your hand, put it on the
fruit shelf. If you have a box of lettuce in your hand, put it on the vegetable shelf.

In VBA we can write them with a decision in long


59 form or in short form:
In jump
VBA If-Then-Else
• there are the statement;
to a designated place and
following completed
continueto
statements with
from End If
there.
realize such queries:
• For clarity,
• IIF function this variant is for max. three queries / decisions makes sense.
A••querySelect
Only worksCase
useful statement;
after
for aan / completed
operation
query decision. withfollowing
with the End Select. program section. If the condition is true, this
section will be processed and if not,
• If-Then-Else statement; completed with End If another section will be processed.
6.1.1• For clarity,
EXCEL VBA: IIfthisFunction
INTRODUCTION variant is for max. three queries / decisions Program makesbranch
sequence, sense. und loops
In• VBA there are
Selectdecisions, the following
Case statement; statements
completed to
with If realize
End such queries:
For simpler there is the Iif decision. weSelect.
have only one decision, we can easily query them
• IIF function
with the IIf function. Our example may look like this:
6.1.2
6.1.1 • IF Only
… IIfuseful
THEN forELSE

Functiona query / decision.
STATEMENT
• If-Then-Else statement; completed with End If
Subsimpler
For Movie ticket_with_Iif()
decisions, there is is
the
A commonly
• For used decision
clarity, this variant ifisIif
...
fordecision.
Then If
max....three wequeries
Else. have
We know only one
this decision,
process
/ decisions makes we
from can easily
Excel
sense. as query
an them
Note
with the = InputBox("Well, what grade did you get?")
if-then • IIf function.
Select
function. Case Our examplecompleted
statement; may look with like this:
End
likeisSelect.
MsgBox IIf(NoteHow does Note
> 2 And it work? < 3, They work
" Good, here ayour
vegetable
movieand fruit
ticket. shop.
Have You "Sorry.")
fun!", get a
End
Sub Sub
newMovie ticket_with_Iif()
delivery. You should then put the goods on the right shelf. If you have a box of apples
6.1.1 IIf Function
Note = InputBox("Well, what grade did you get?")
inForyour hand, put it onthere
the fruit shelf. If you Ifhave a boxonlyof lettuce in yourwehand, put itquery them
6.1.2
MsgBoxsimpler If …> Then
decisions,
IIf(Note 2 And Note… is theElse
< 3, statement
Iif "decision.
Good, here we ishave
your movie one decision,
ticket. can easily
Have fun!", "Sorry.")
on
End withthethe
Sub vegetable shelf.Our example may look like this:
IIf function.
A commonly used decision is if ... Then ... Else. We know this process from Excel as an if-then
function. How does it work? They work like a vegetable and fruit shop. You get a new delivery. You
Sub Movie ticket_with_Iif()
6.1.2 If the
… Then … Else statement
should
In VBAthen
we put
can goods
write themon the
with right shelf. in
a decision If long
you have
formaorbox
in of apples
short in your hand, put it on the
form:
Note = InputBox("Well, what grade did you get?")
Afruit shelf. If used
commonly you have
MsgBox IIf(Note
a boxisofif lettuce
decision
> 2 And Note... <
Thenin your
3, " ...
Good,
hand,
Else. Weput
here
it on the process
isknow
your this
vegetable shelf.
movie ticket.fromHaveExcel
fun!",as an if-then
"Sorry.")
function.
End Sub How does it work? They work like a vegetable and fruit shop. You get a new delivery. You
In VBA we can write them with a decision in long form or in short form:
should then put the goods on the right shelf. If you have a box of apples in your hand, put it on the
fruit shelf. If you have a box of lettuce in your hand, put it on the vegetable shelf.
Langform:
6.1.2
Langform: If … Then … Else statement
In AIf
VBAgrade
commonly<= write
we can 3used
Then decision
them withisa if ... Then
decision ... Else.
in long formWe know
or in shortthis process from Excel as an if-then
form:
MsgBoxHow
function. “Good,
doeshere is your
it work? Theymovie
workticket.
like aHave fun.“ and fruit shop. You get a new delivery. You
vegetable
End
should
Langform:If then put the goods on the right shelf. If you have a box of apples in your hand, put it on the
fruit shelf.
If grade <=If3you
Thenhave a box of lettuce in your hand, put it on the vegetable shelf.
Shortform:
MsgBox “Good, here is your movie ticket. Have fun.“
If grade
In
End VBA
If we <= 3 Then
can write MsgBox
them with “Good, here isinyour
a decision longmovie
form or ticket. Have
in short fun.“
form:
Shortform:
AnLangform:
individual query is rarely used in practice. Most queries are at least two, three, or more. Now let's
Shortform:
look Ifatgrade
If grade simple
<=<= 3toThen
3complex
ThenMsgBox examples.
“Good, here is your movie ticket. Have fun.“
MsgBox “Good, here is your movie ticket. Have fun.“
Forindividual
An example,
End If suppose
query you want
is rarely used toin give yourMost
practice. childqueries
a movieare
ticket, buttwo,
at least it depends onmore.
three, or his/her
Nowgrades.
let's
If he/she
look at receives
simple to better than
complex a 3, then your child will get the movie ticket. If they receive lower than
examples.
An individual query is rarely used in practice. Most queries are at least two, three, or more.
a Shortform:
3, they will not.
ForNow let’s look
If grade
example, <= at
suppose simple
3 Then you to
MsgBox complex
want “Good,
to giveexamples.
here child
your is your ticket. but
a movie ticket, Haveit fun.“
depends on his/her grades.
IfVBA codereceives
he/she might look likethan
better this:a 3, then your child will get the movie ticket. If they receive lower than
a 3,Anthey
individual
will not.query is rarely used in practice. Most queries are at least two, three, or more. Now let's
For
Sublook example,
at simplesuppose
Movie_Ticket() to complex you want to give your child a movie ticket, but it depends on his/
examples.
grade=InputBox(“Well,
VBAhercode
grades. If he/she
might look like what
this:grade
receives betterdid youa get?“)
than 3, then your child will get the movie ticket. If
For example, suppose you want to give your child a movie ticket, but it depends on his/her grades.
they receive lower than a 3, they will not.
Sub If Movie_Ticket()
he/she receives better than a 3, then your child will get the movie ticket. If they receive lower than
a 3, they will not.
grade=InputBox(“Well, what grade did you get?“)
VBA code might look like this:
VBA code might look like this:

Sub Movie_Ticket()
grade=InputBox(“Well, what grade did you get?“)

If grade <= 3 Then


MsgBox “Good, here is your movie ticket. Have fun.“
Else
MsgBox “Sorry.“
End If
End Sub

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

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 message. It is written at the end of the listing with the variable “content” AND
with active cell content.

Firstly, this is clearer and secondly, it is more adaptable or adjustable.

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

6.1.3 SELECT CASE-; END SELECT STATEMENT

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

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

Discover our eBooks on


Time Management Skills
and hundreds more

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.

Again, there are different loop instructions:

¾¾ For...Next statement
¾¾ While…Wend statement
¾¾ Do...Loop statement

Now let’s take a look at them with examples:

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 used here, e.g. “I”, tells you how many times the loop should
go through. The 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 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

Figure 53: For...Next loop backward


Figure
Figure 53:53:
For...Next
For...Nextloop backward
loop backward

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

EXCEL VBA: INTRODUCTION Program sequence, branch und loops


Now a combination with If...Then...Else decisions. The run in the lower example runs with three steps
Figure
backward and is conditionally terminated prematurely. 54: For...Next
Once the value loop backward
i is less than 3, exit with Exit
For before appearing in the immediate area. So, i = i – 3.

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

Figure 56: Select value from sheet

Figure 56: Select value from sheet


Now I just want to show a part of the practical example. We will come back to these topics
later. Here is an example to make sense of the For-Next statement.
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”.

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
.
.

6.2.2 FOR EACH ... NEXT STATEMENT


6.2.2
For Each...NextFor Each is...mostly
- statement Next Statement
used on objects. These objects may be cells, spreadsheets
For Each...Next - statement is mostly used on objects. These objects may be cells, spreadsheets etc.
6.2.2
etc. For Each ... Next Statement
For
ThisEach...Next - statement
loop repeats is for
instructions mostly used on objects.
all elements of a dataThese objects
field with the may be cells,
number spreadsheets
of passes equaling etc.
the
number of elements.
This loop repeats instructions for all elements of a data field with the number of passes
This loop repeats instructions for all elements of a data field with the number of passes equaling the
equaling
number theelements.
of number of elements.
I think two examples suffice. We will use For Each..Next statement a bit more later on.

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

In the example below, all worksheets are output.


In the example below, all worksheets are output.

In the example below, all worksheets are output.

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

6.2.3 DO...LOOP STATEMENT

There are two types of von Do…Loop statement:

¾¾ 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

Figure 59: Search with Do…Loop_1


Figure 59: Search with Do…Loop_1
Figure 59: Search with Do…Loop_1
It is searched until an empty cell is found.
It is searched until an empty cell is found.
It is searched until an empty cell is found.
Sub DoWhileLoop_statement_2()
i=1
Sub DoWhileLoop_statement_2()
Do While Range("A" & i) <> ""
i=1
Debug.Print Range("A" & i)
Do While Range("A" & i) <> ""
i=i+1
Debug.Print Range("A" & i)
Loop
i=i+1
Debug.Print “Next empty cell is in: “ & Range("A" & i).Address
Loop
End Sub
Debug.Print “Next empty cell is in: “ & Range("A" & i).Address
End Sub

69
EXCEL VBA: INTRODUCTION Program sequence, branch und loops

Figure 60: Suchen_2 Do...Loop


Figure
Figure 60:
60: Suchen_2
Suchen_2 Do...Loop
Do...Loop
The next two examples are with the Do ... Until ... Loop statement. The result of this
statement
The
The next
is
next two
theexamples
same as before.
two examples are
are with
The
with the
difference
the Do
Do ...
next...toLoop
... Until
Until ...
the statement.
Until statement
Loop statement. The is the operator.
The result
result of
of this
this statement
statement is
is
the
Here same as
an equal
the same before. The
sign (=)The
as before. difference
is used next
insteadnext
difference to the
of “Smaller Until statement
(<) and
to the Until is the
Larger is(>)”
statement operator.
thecharacters. Here an equal sign
operator. Here an equal sign
(=)
(=) is
is used
used instead
instead of
of "Smaller
"Smaller (<)
(<) and
and Larger
Larger (>)"
(>)" characters.
characters.

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

Figure 62: Search with Do...Until_2

6.2.4 WHILE…WEND STATEMENT


6.2.4 While…Wend Statement
While ... Wend statement is executed until the desired operation occurs.
While ... Wend statement is executed until the desired operation occurs.

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

Figure 63: Search with While..Wend


Figure 63: Search with While..Wend

6.2.5 WITH...END WITH STATEMENT

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.

Between the With


This example and End With
demonstrates howstatements weWith
a With...End first define "where",
statement then
works. "what"
Long andcan
listings "how"
be to display
or format. For example, in "cell", "font" should be displayed in bold.
seen when macros record. We will see more about macros later on.
This example demonstrates how a With...End With statement works. Long listings can be seen when
macros
On therecord.
left isWe will see more
a recorded about
macro. Onmacros later on.
the right-hand side is the optimized macro.
All the
On itemsleftthat
is awere not changed
recorded during
macro. On recording are
the right-hand recorded
side as “False” macro.
is the optimized or “0”. These can
All
be items
easily that were Stacking
removed. not changed duringstatements
the With recording minimizes
are recordedtheaslisting
"False"
byor "0". lines.
a few These can be easily
removed. Stacking the With statements minimizes the listing by a few lines.

Sub Recorded_macro() Sub Optimized_macro()


' '
ActiveCell.FormulaR1C1 = "Harun" With ActiveCell
With Selection.Interior .Interior.ColorIndex = 34
.ColorIndex = 34 .Value = "Harun"
End With .HorizontalAlignment = xlLeft
Selection.Font.Bold = True .VerticalAlignment = xlBottom
Selection.Font.ColorIndex = 5 .ReadingOrder = xlContext
With Selection.Font ‘
.Name = "Arial" With .Font
.Size = 12 .Bold = True
.Strikethrough = False .Name = "Arial"
.Superscript = False .Size = 12
.Subscript = False .ColorIndex = 5
.OutlineFont = False End With
.Shadow = False End With
.Underline = xlUnderlineStyleNone End Sub
.ColorIndex = 5
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End Sub

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

EXCEL VBA: INTRODUCTION Program sequence, branch und loops


In the second example, the column and the row of the active cell are set to the optimal 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

6.3 BRANCH STATEMENT


A jump instruction is like a lift in a mall. As soon as you are in the elevator, press the
button for the floor you want to go to (decision / jumps). If you are on the floor, continue
shopping (program cuts).

Such jumps are executed when a condition occurs or enters directly. There are two types:

DDA conditional jump, which is possible after a condition


If..Then..Else or Select Case.

DDAn UNconditional jump, which continues from the given VBA-code line / jump point,
GoTo or GoSub…Return.

Here are some examples to help make it easier to understand.

6.3.1 GOTO STATEMENT

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.

6.3.1 GoTo Statement


EXCEL VBA: INTRODUCTION Program sequence, branch und loops
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.

Sub GoTo_Examplel()
grade = InputBox("Well, which grade did you get?")

If grade > 1 And grade < 2 Then GoTo grade_1_2

Select Case grade


Case 2 To 3
GoTo grade_2_3
Case 4 To 5
GoTo grade_4_5
Case Is > 6
GoTo Ending
End Select

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

6.3.2 GOSUB-; RETURN STATEMENT

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. 

Here is an example with GoSub / Return / Select-Case:

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

Here is an example with GoSub / Return / Select-Case:

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.

Here’s the same example with If-Then

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

Figure 64: Result of GoSub


Figure 64: Result of GoSub

76
EXCEL VBA: INTRODUCTION Communication with Excel

7 COMMUNICATION WITH EXCEL


What is communication? The dictionary says:

• Communication between people using language or signs


• The exchange of information between devices

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.

We have seen these communication messages very often. For example

• with an error message

Figure 65: An Error message

• also with the settings in Excel up to version 2010

Figure 66: Format Cells

77
EXCEL VBA: INTRODUCTION Communication with Excel

• and also with the settings in Excel from version

Figure 67: Settings in Excel from Version 2010

Using VBA instructions, we can display such messages or masks in different ways and make
them appear on the desktop:

• “InputBox = input field” and “MsgBox = output field”


• Dialog mask “UserForm” (later on in Book IV)

7.1 MESSAGE WINDOW


The message box MsgBox “Message Box” is often used in VBA. MsgBox is set to an output message
on the screen. MsgBox has at least one “OK” button to confirm. Each button has a return value in the
background to distinguish which key is pressed. The selected key then returns a value of type Integer.
The message is waiting for a button displayed inside it to be clicked.

The syntax of the MsgBox function with its arguments:


MsgBox (prompt [, buttons] [, title])

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

Figure 68: Example MsgBox_1


Sub MsgBox_Title()
MsgBox "I learn VBA.", _
Sub MsgBox_Title()
Title:=“My Message“
MsgBox
End Sub "I learn VBA.", _
Title:=“My Message“
End Sub

Figure 69: Example MsgBox_2


Figure 69: Example MsgBox_2
Figure 69: Example MsgBox_2
7.1.1 Buttons in Message window
A simple message window has at least one OK button. In addition, other buttons may be displayed.
7.1.1 Buttons in Message window
This can be used in VBA code with a constant or with their values. Available buttons are as follows:
A simple message window has at least one OK button. In addition, other buttons may be displayed.
7.1.1 BUTTONS IN MESSAGE WINDOW
This can be used in VBA code with a constant or with their values. Available buttons are as follows:
Constant Value Button
A simple message window has at least one OK button. In addition, other buttons may be
vbOKOnly
displayed. This can be used in VBA code
Constant 0with a constant
Value OK
Button or with their values. Available
buttons are as follows:
vbOKCancel
vbOKOnly 1
0 OK
OK and Cancel
vbAbortRetryIgnore
vbOKCancel 2
1 Cancel,
OK and Retry
Canceland Ignore
Constant
vbYesNoCancel Value
3 Yes, No Retry
und Cancel Button
vbAbortRetryIgnore 2 Cancel, and Ignore
vbYesNo
vbYesNoCancel
vbOKOnly 4
30 Yes
Yes,and No Cancel
No und OK
vbRetryCancel
vbYesNo 5
41 Retry and
Yes and NoCancelOK and Cancel
vbOKCancel
Table 3: Constant of MsgBox
vbRetryCancel 5 Retry and Cancel
vbAbortRetryIgnore 2 Cancel, Retry and Ignore
IfTable 3: Constant
you want of MsgBox
to display additional buttons other than OK, such as Cancel, either with a constant or the
value button then these buttons must be programmed
vbYesNoCancel 3 accordingly.
Yes,In
Nothe
undsame section as the "OK"
Cancel
If you want
button to display
you will additional
also find "Cancel".buttons other than either
In programming, OK, such
the as Cancel,
If ... either
Then ... Elsewith a constant
or the Select ...or the
Case
value button then
statementvbYesNo these buttons must be programmed
is used. Both variants are displayed4 below. accordingly. In the same
Yes and No 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
vbRetryCancel 5 below. Retry and Cancel

Table 3: Constant of MsgBox

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

First, the example with “OK”:


First, the example with "OK":
First, the example with "OK":
First, the example with "OK":
Sub MsgBox_1()
Sub MsgBox_1()
MsgBox "VBA-Programming“
Sub
End MsgBox_1()
MsgBox
Sub "VBA-Programming“
MsgBox
End Sub "VBA-Programming“
End Sub

Figure 70: OK Button only


Figure 70: OK Button only
Figure 70: OK Button only
Figure 70: OK Button only
Now “Cancel” comes into play. If there are two buttons, we have to add the clicked button
Now "Cancel" comes into play. If there are two buttons, we have to add the clicked button to a value.
to
Now
Thea value.
exampleThecomes
"Cancel" example
into“Msgbox_2_1”
"Msgbox_2_1" play.with
If there with
are twoaand
a constant constant
buttons, and
we theto
have
the example example
add the“Msgbox_2_2”
clicked
"Msgbox_2_2" button
with to a value.
the value of a
Now
The "Cancel"
example
constant. Bothcomes into
"Msgbox_2_1"
have the play.
same If
withthere
a
result. are two
constant buttons,
and the we have
example to add the clicked
"Msgbox_2_2" button
with the to a value.
value of a
with the value "Msgbox_2_1"
The example of a constant. Both
with have the same
a constant andresult.
the example "Msgbox_2_2" with the value of a
constant. Both have the same result.
constant. Both have the same result.
Sub MsgBox_2_1()
Sub MsgBox_2_1()
Wert=MsgBox ("VBA-Programming“, _
Sub MsgBox_2_1()
Wert=MsgBox ("VBA-Programming“, _
Buttons:=vbOKCancel)
Wert=MsgBox
End ("VBA-Programming“, _
SubButtons:=vbOKCancel)
End SubButtons:=vbOKCancel)
End MsgBox_2_2()
Sub Sub
Sub MsgBox_2_2()
Wert=MsgBox ("VBA-Programming“, _
Sub MsgBox_2_2()
Wert=MsgBox ("VBA-Programming“, _
Buttons:=1)
Wert=MsgBox
End ("VBA-Programming“, _
SubButtons:=1)
End SubButtons:=1) Figure 71: With OK and Cancel buttons
End Sub Figure 71: With OK and Cancel buttons
Figure 71: With OK and Cancel buttons
Figure 71: With OK and Cancel buttons
Now with “Cancel”, “Repeat” and “Ignore“:
Now with "Cancel", "Repeat" and "Ignore“:
Now with "Cancel", "Repeat" and "Ignore“:
Now
Sub with "Cancel", "Repeat" and "Ignore“:
MsgBox_3_1()
Sub MsgBox_3_1()
Wert=MsgBox ("VBA Programming“, _
Sub MsgBox_3_1()
Wert=MsgBox ("VBA Programming“, _
Buttons:= vbAbortRetryIgnore)
Wert=MsgBox
End SubButtons:=("VBA Programming“, _
vbAbortRetryIgnore)
End Sub Buttons:= vbAbortRetryIgnore)
End Sub
Sub MsgBox_3_2()
Sub MsgBox_3_2()
Wert=MsgBox ("VBA Programming“, _
Sub MsgBox_3_2()
Wert=MsgBox ("VBA Programming“, _
Buttons:=2)
Wert=MsgBox
End Sub ("VBA Programming“, _
Buttons:=2) Figure
Figure 72: 72: With
With three three
buttons buttons
End Sub Buttons:=2) Figure 72: With three buttons
End Sub Figure 72: With three buttons
Now we have to program which section should be executed according to the selected button.
This is possible with the return value of the selected button. With the “OK” selection we
have the “value = 1” and with “Cancel” selection the “value = 2”.
The table below lists all the return values.

Constants and (return) values of the individual buttons are as follow:

80
EXCEL VBA: INTRODUCTION Communication with Excel

Constant Value Button

vbOK 1 OK

vbCancel 2 Cancel

vbAbort 3 Abort

vbRetry 4 Retry

vbIgnore 5 Ignore

vbYes 6 Yes

vbNo 7 No

Table 4: Return values of a button

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 = MsgBox("I learn VBA.", _


Sub MsgBox_Button_If()
Buttons:=1, _
Dim intAnswer As Integer
Title:="My Message")

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

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 and system-internal constants for tab and breaks.

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

Constant ASCII Description


Constant ASCII Description
vbTab Chr(9) Tabulator
vbTab Chr(9) Tabulator
vbLf Chr(10) Line Feed – neue Zeile einfügen -
vbCr vbLf Chr(13) Chr(10) Line
Carriange Return – Feed – neue Zeile
Zeilenumbruch - einfügen -

vbCr Chr(13) Carriange Return – Zeilenumbruch -

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

'Result entered in cell “A1”


Range("A1").Value = ("Hello " & strFirstName & vbLf & vbLf & _
"Congratulations to your first child." & Chr(10) & _
Chr(10) & vbCr & _
Date & vbTab & Time)
End Sub

Figure 74: 74:


Figure Output in in
Output MsgBox
MsgBox Figure
Figure 75:75: Result
Result entered
entered in cell in cell

7.3 SYMBOL IN MESSAGE WINDOW


In the message window not only titles, text and buttons can be placed, but additional
symbols can be placed as well. This symbol classifies the content of the message, whether
the message is a warning, a question, or information, for example.

83
EXCEL VBA: INTRODUCTION Communication with Excel

7.3 Symbol in Message window


In the message window not only titles, text and buttons can be placed, but additional symbols can
be placed as well. This symbol classifies the content of the message,
Constant Symbol whether the message is a
warning, a question, or information, for example.
vbCritical Stop
Constant Symbol
vbQuestion Question mark
vbCritical Stop
vbExclamation Exclamation mark
vbQuestion Question mark

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

Figure 76: Symbol Figure 76: Symbol in Message window


in Message window

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

Figure 77: An example with vbSystemModal

The constant vbSystemModal causes the message in the foreground to freeze if other
programs are also used.

7.4 INPUT WINDOW


The input window, InputBox is the opposite of the output window, MsgBox. As the name
implies, this window has an input field and by default contains “OK” and “Cancel” buttons.
The select switch then returns a value of type Integer. This value is needed to query which
button the user clicked.

The user is prompted

• 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

Figure 78: InputBox and MsgBox


Figure 78: InputBox and MsgBox
Figure 78: InputBox and MsgBox

Sub Message_area_Inputbox() 'with Inputbox


SubstrName,
Dim Message_area_Inputbox() 'with Inputbox
strFirstname, strAddress, strInfo As String
Dim strName, strFirstname, strAddress,
strName = InputBox("Please enter your name: strInfo ")
As String
strName = InputBox("Please enter your name:
strFirstname = InputBox("Please enter your first name: ") ")
strAddress = InputBox("Please enter your street: ")name: ")
strFirstname = InputBox("Please enter your first
strAddress
strInfo = InputBox("Please
= MsgBox(("Name enter your
: " & strName street:
& vbCr & _")
strInfo = MsgBox(("Name
"First name : " & strFirstname &&vbCr
: " & strName & vbCr _ &_
"First name : " & strFirstname & vbCr & _
"Address : " & strAddress), , "Information")
End Sub "Address : " & strAddress), , "Information")
End Sub

Figure 79: MsgBox with more InputBox


Figure 79: MsgBox with more InputBox
Now the practical example from earlier with extension:
Now the practical example from earlier with extension:

Figure 79: MsgBox with more InputBox

86
EXCEL VBA: INTRODUCTION Communication with Excel

Now the practical example from earlier with extension:

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

Online Microsoft Developer Network:


https://msdn.microsoft.com/de-de/vba/office-vba-reference

88

You might also like