Excel VB A Introduction
Excel VB A Introduction
ISBN 978-87-403-3858-4
Contents
Introduction
2 Developer Environment
2.1 VBA-Editor Environment
Bibliography
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 for this book is therefore both beginners as well as users up
to advanced level.
There are already different books and online guides available. So you ask
yourself “What’s so special about this book?”.
The special feature of the book is that it finds its origin in practice and this
can be excellently used as a reference book. The storage locations are not
only local places like hard disks, 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:
Harun Kaplan
For my Family:
Tülay
However, with the functions already integrated in Excel you will reach the
limits.
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.
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”.
If 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
1. VBA-Editor
2. Project Editor
3. Properties
4. Watches
5. Immediate
6. Locals
The most important segment of the VBA environment is the VBA program editor.
VBA provides its own windows for each workbook, for each sheet and for the
forms. Here the program code of the modules is entered. Recorded or manually
created program parts can be called up, adapted or even modified here.
The VBA editor is not visible when you first open an Excel file. We find it in the
“Insert | Module” menu.
The editor writes program sections with individual commands, definitions, and
comments according to VBA syntax rules. If the syntax of the VBA code is
correct, the first letters are converted to uppercase. Otherwise there is a typo.
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
As shown in Figure 5, after opening the Project Explorer, you will see
“ThisWorkbook” and at least one “Table”.
Figure 5: Project
Callable via
The following figure shows two different design representations of a combo box
properties 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 “.
Via menu “Debug | Add watch “. Once a variable in the “Add Watch” is
confirmed, the watch window appears:
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.
2.1.5 Immediate
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
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.
All Office programs have a macro recorder which allows all actions to be recorded. The
resulting macros are the preliminary stage of VBA programming.
Therefore, it is useful to initially record and optimize many macros in the beginning. That is
why I call this experience “learning by recording”. The more macros we record and then
optimize, the faster we will get into the world of VBA programming and feel “at ease”
there.
The recorded macros are used to automate the Excel operation. Recording records all
consecutive actions. The recording is rigid and runs exactly as it was also recorded.
A recorded macro is indeed a very useful tool, unfortunately only with limited automation of
processes. Therefore, we quickly reach the limits of macro recording.
The key combination ALT + F11 leads us directly into the area of the editor. In the recorded
macro, the syntax and logic of Excel can be analyzed. Change one or more values and you
can see the differences after restarting
Absolute recording
A rigid recording, regardless of the current position of the cursor the same cells are
always addressed.
Relative recording
Just like 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. 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:
Procedure header or also the declaration part: Here the variables occurring in the
procedure are declared.
VBA 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.
When the recording is started, the Record Macro dialog box appears. If you wish, we can
fill in the following information about the macro before starting:
After pressing the OK button, the recording is started. I have marked cells A1 through A5.
The list is shown in Figure 15.
The recording of a procedure is similar to a toddler who explores and gets to know its
surroundings by touching. Again, you learn the individual commands and their spelling.
We start our macro recorder via the menu “Developer | Record macro “.
First we mark the area “A1: C4”, then we call the mask “Format cells”. There we define the
settings in the “Numbers” tab to three decimal places, in the “Font” tab to “Bold” and a font
size of “16”.
Sub Macro_reckording()
‘Macro1 Macro
‘Example for Reckording a macro.
‘Keyboard Shortcut: Ctrg+b
Range(“A1:C4”).Select
Selection.NumberFormat = “0.000”
With Selection.Font
.Name = “Calibri”
.FontStyle = “Fett”
.Size = 16
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
End Sub
Unmodified formatting will either have the default settings or they will have the following
entries, such as “False”; “XlNone”; “XlAutomatic”; “0”; or “None” ending. These
unnecessary additional entries make our macros longer and more confusing.
Sub Macro_recording()
Range(“A1:C4”).Select
Selection.NumberFormat = “0.000”
‘Register Schrift
With Selection.Font
.FontStyle = “Fett”
.Size = 16
End With
End Sub
An absolute recording rigidly formats certain areas. A relative recording is started from the
current cell.
We can use the previous absolute record as an example. We will now convert it into a
relative record. For this purpose, the statement ActiveCell is entered in front of the range
(“D10: F12”) 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
Sub Makro_Recording()
Range(“D10:F12”).Select
.
.
.
End Sub
End Sub
I would like to repeat my adage: The more we record and analyze the recording, the more
we master VBA programming.
The relative recording is recorded like the absolute recording. The only difference is that
the button “Use relative references” is selected before the recording.
Now a macro with the same content and with different recordings.
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
Range(“D10:F12”).Select
With Selection.Interior
.Pattern = xlSolid
.Color = 3
End With
Range(“D10”).Select
End Sub
In the relative record, starting at the cursor position, the next three column cells and the next
three row cells are marked and formatting is performed.
Sub Relative_recording()
‘ Relative_recording macro => show Figure 18
ActiveCell.Range(“A1:C3”).Select
With Selection.Interior
.Pattern = xlSolid
.Color = 3
End With
ActiveCell.Select
End Sub
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”.
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.
Such buttons can be created from a toolbar of the form, the Autoforms, or the controls
Toolbox.
“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.
The “Application.Run” statement will open a macro or function from an external Excel file.
The security settings are an important topic in Excel. Any open Excel file may contain
dangerous macros. Therefore, it is recommended to set the security setting to at least the
middle position. When set, it will open a dialog box when opening an Excel file that
contains macros. In it we can still decide whether to open the file call with or without
macro activation.
You get these when the menu command “Developer | Macro Security “is displayed. The
Security dialog allows you to create different settings.
4 Script concept by VBA
Before delving into the world of VBA language elements, I would like to explain
some prerequisites for VBA programming.
With the VBA programming we can extensively exhaust the possibilities of Excel.
Reasons for this can be the following:
As you know, the way to love is through the stomach. This analogy includes
vegetables, meat, fish, a few different spices, and so on to other ingredients. All
these ingredients are mixed according to our wishes in a specific order to make a
hopefully delicious meal out of it.
With VBA, we can address from the top level down to the lowest level. These
levels are:
They start with the statement Sub Name_Procedure () and end with End Sub:
Sub Say_hello_1()
End Sub
You can do this with icons in 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” the lines are movied to the left.
Figure 26: Indenting (Tab) / Outdenting (Shift+Tab)
‘Outdenting
For x = 1 To 5
If name = “Harun” Then
Range(“A” & x).Value = name & “_” & x
Else
Range(“B” & x).Value = name & “_” & x
End If
Next x
‘Indenting
For x = 1 To 5
If name = “Harun” Then
Range(“A” & x).Value = name & “_” & x
Else
Range(“B” & x).Value = name & “_” & x
End If
Next x
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.
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.
In Excel:
=CountIf(C:C;”Stuttgart”)
In VBA:
Sections of text starting with an apostrophe are marked as comments by the VBA
editor. They are not executed.
End Sub
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.
The IntelliSense collection also appears after an equals sign of an object, but
constants are offered this time.
Quick help for the syntax of functions, methods or procedures is a good help. If,
for example, a method is entered, a short reference with the necessary and
possible arguments appears directly below the insertion point after entering the
next empty space or an open parenthesis.
The arguments in square brackets are optional. All others are to be entered.
Example 1:
The tooltip of “Offset” tells us that after an open parenthesis all necessary
arguments are listed. Commonly needed arguments are in parentheses and the
currently needed argument is shown in bold type.
Example 2:
Figure 31: Quick info-Examples of MsgBox with arguments
If you run your procedure step-by-step with F8, you will also get tool tips for the
current VBA line. This is marked in color by positioning the mouse pointer.
In the following example, the variable “Response” is assigned the address of the
active cell. When we move the mouse pointer to “answer”, the assigned value
appears as a tooltip.
Long or very long VBA instruction lines can’t always be avoided in the VBA
editor. A space combined with an underscore helps us to present our
programming in a more structured way. The underscore is entered immediately
after the space. This tells the VBA editor that the statement line has not yet ended.
This has the advantage that the entire VBA line is visible. However, the break
can’t happen anywhere. It is only allowed in front of or behind an element of
expression.
No comment may be inserted after the underscore. Sequences in strings must be
terminated with a quotation mark and linked with the join operator “&” and is
called concatenation. This can combine two or more strings to from a new string.
Sub Example_VBA_Syntax_gap()
Dim strName, strfirstname, strAddress As String
strname=”Max”
strfirstname=”Mustermann”
‘Without gap
MsgBox (“Name: “ & strname & Chr(10) & “First Name: “ & strfirstname &
Chr(10) & “Address: “ & straddress)
‘With gap
MsgBox (“Name: “ & strname & Chr(10) & _
“First Name: “ & strfirstname & Chr(10) & _
“Adresse: “ & straddress)
End Sub
The properties of the variables are set at the beginning of the procedure with the
Dim keyword. These definitions can be numerical values, texts or objects.
The naming of the variables follows the following rules:
The variable abbreviations are set by us, but they also indicate their origin. For
example, an integer number with “intNumber” means that the variable number
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
intNumber = 231
strName = “Harun”
blnAntwort = True
bytValue = 1
End Sub
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.
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”.
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:
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
End Sub
Figure 33: Example Date-type_1
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
vb from VBA-Object-Library
xl from Excel
fm from MSForms-Library
mso from MS-Office
grd from Toolbox-Sheet.
The figure above shows two procedures in “Module1” with an output of the first
procedure. We have declared the variable “intValue” in procedure
“Gültigkeitsbereich_1” and the variable “strText” in procedure “Validity_Range
_2”.
“IntValue” only applies in the upper procedure and “strText” only in the lower
procedure.
Validity within a module means that a variable is valid in all procedures. This
variable is declared outside the procedures.
End Sub
End Sub
End Sub
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:
Now let’s look at a function. Here we calculate the circular area by passing the
radius with the line “dblResult = Calculation (5)” to the “Function
dblCalculation”. The calculated value is output in the procedure
“dblCalculatation”.
If the variables are to be valid in all modules, then we declare these variables,
for example in module1, with the Public statement. That is, these variables are
provided by all modules in all procedures.
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.
What is the second run? The x value will still remain “1” and the y value will
continue to increase by “1”.
So far we have declared our variables with the Dim statement. Such variables are
provided by either an input or a result of calculation or the like.
The Set-variables, on the other hand, are fixed components of the excel.
Such Excel objects are:
VBA syntax starts with Set, followed by Object variable, then Excel object type.
An example:
We have two tables, “Sheet1” and “Sheet2”. Cell “A1” of Sheet1 has the value
“1923”. It should be multiplied by the value “2.5” and the product entered in cell
“A1” of table2.
Sub Exaple_without_Set()
Worksheets(“Sheet1”).Range(“a1”).Value = 1923
Worksheets(“Sheet2”).Range(“a1”).Value =
Worksheets(“Sheet1”).Range(“a1”).Value * 2.5
End Sub
Sub Example_with_Set()
Dim Cell1 As Range
Dim Cell2 As Range
‘
Set Cell1 = Worksheets(“Sheet1”).Range(“A1”)
Set Cell2 = Worksheets(“Sheet2”).Range(“A1”)
‘
Cell1 = 1923
Cell2 = Cell1 * 2.5
End Sub
The user-defined data types are assembled from the basic types listed above
using the Type statement. They are listed between the following keywords:
Option Explicit
End Type
End Type
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!
Sub Constants_1()
‘VAT
Const VAT As Single = 0.19
‘Filename
Const Filename As String = “Constant.xlsx”
Const strPath As String = “C:\Harun\”
Const strPath_all As String = “C:\Harun\Constant.xlsx”
‘Dim’s
Dim Value_1 As Integer
Dim Text_1 As String
Value_1 = 2321
Text_1 = “Text Text”
Debug.Print “VAT is: “ & vbCr & VAT & “%” & Chr(10)
Debug.Print “File name is: “ & Chr(13) & Dateiname & vbLf
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
Debug.Print “Text is: “ & Chr(13) & Text_1 & vbLf
End Sub
Figure 42: Result of Constants_1
If we write like this below, we will get an error message. A const value must not
be changed. This procedure works with Dim VAT As Integer:
Sub Constants_2() ‘
Const VAT As Single = 0.19
VAT=VAT + 1
MsgBox VAT
End Sub
There are also many (system) integrated constants in VBA. They begin with the
prefix
vb Visual Basic
xl Excel.
For example, the following color constants can be used directly throughout the
code:
In this example, the active cell is displayed with a green background color.
Sub VBA_Constant()
ActiveCell.Interior.Color = vbGreen
End Sub
These serve to carry out calculations. My first example will be with the values
from the examples 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
End Sub
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
(12 + 3) * 5 = 75
Comparison operators can be applied to almost all data types. The result of the
comparison is a truth value - either
TRUE
correct,
FALSE
not correct.
Sub IS_Compare()
Dim Object1, NewObject, Object2, Object3, Object4, Test1
Set NewObject = Object1 ‘ Object allocation
Set Object2 = Object1
Set Object4 = Object3
Test1 = NewObject Is Object2 ‘ result true.
Test1 = Object4 Is Object2 ‘ result false.
‘ Accepted: Object1 <> Object3
Test1 = Object1 Is Object4 ‘ result False.
End Sub
If both Object1 and Object2 refer to the same object, the result is TRUE,
otherwise the result is FALSE.
End Sub
The emergency operator only affects operands, all other logical operators
become Linking 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
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.
There are also different reactions to these error messages. For example, in
typing errors the whole VBA code line will appear in red.
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.
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.
Sub Worksheet_not_exist_2()
‘Worksheet “Harun” does not exist!
On Error Resume Next
Worksheets(“Harun”).Activate
On Error Goto 0
‘Worksheet “Harun” does not exist, too!
Worksheets(“Kaplan”).Activate
End Sub
Sub Worksheet_does_not_exist3()
‘Worksheet “Harun” does not exist!
On Error GoTo Meldung
Worksheets(“Harun”).Activate
‘
‘other VBA-Code line
‘
Meldung:
MsgBox “ In case of error, I will be redirected here!”
End Sub
Now let’s have a look at the individual icons with their tasks.
The macro can be executed in single step mode also named “Step by
Step“.
The current line is marked on the left bar with a yellow arrow and the line is
highlighted in yellow.
If you want to know the contents of the variable, just move the mouse pointer
over the variable. A tooltip displays the content of the variable.
When debugging in a single step, the current line is highlighted in yellow and
marked with a yellow arrow in the bar to the left of the code.
The Toggle breakpoint serves to stop the drain at this point. The activated
line is marked with a red dot. The line is saved with the same color.
The program automatically runs through to the breakpoint and stops at the
breakpoint.
5.3.4 Bookmarks
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
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.
A query works after an operation with the following program section. If the
condition is true, this section will be processed and if not, another section
will be processed.
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 Case statement; completed with End Select.
6.1.1 IIf Function
For simpler decisions, there is the Iif decision. If we have only one decision,
we can easily query them with the IIf function. Our example may look like
this:
End Sub
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 form or in short form:
Longform:
If grade <= 3 Then
MsgBox “Good, here is your movie ticket. Have fun.“
End If
Shortform:
If grade <= 3 Then MsgBox “Good, here is your movie ticket. Have fun.“
An individual query is rarely used in practice. Most queries are at least two,
three, or more. Now let’s look at simple to complex examples.
For example, suppose you want to give your child a movie ticket, but it
depends on his/her grades. If 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.
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
Sub 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
If grade = 3 Then
MsgBox “Good, here is your movie ticket. Have fun.“
Endif
If grade > 3 Then
MsgBox “You should still learn. Sorry!“
End If
End Sub
We can stack them like a matryoshka nesting doll. Compared to the previous
example, there is a little less typing. Now the same example stacked with
Elseif:
Sub if_statement_with_Elseif()
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. “
Elseif grade = 2 Then
MsgBox “Great. Here is your movie ticket with popcorn. Have fun.“
ElseIf grade = 3 Then
MsgBox “Good, here is your movie ticket. Have fun.“
Else
MsgBox “You should still learn. Sorry.“
End If
End Sub
The If statement has checked fixed notes on previous examples. If entered
with a number, no correct message would appear. Now we have made our
example even more accurate. 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
MsgBox “Good, here is your movie ticket. Have fun.“
Else
MsgBox “You should still learn. Sorry.“
End If
End Sub
The next example checks whether the input corresponds to a value, i.e. no
letter or similar. We check this with IsNumeric:
Sub if_statement_3()
grade =InputBox(“Well, what grade did you get?“)
If IsNumeric(Note) Then
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
MsgBox “Good, here is your movie ticket. Have fun.“
Else
MsgBox “You should still learn. Sorry.“
End If
Else
MsgBox “Please enter your grade!!”
End If
End Sub
If the content contains a number, then a message with cell content appears.
Otherwise, if the content contains a date, then another message with cell
content appears, etc.
Sub Check_cell_value_1()
If IsNumeric(ActiveCell) And ActiveCell <> “” Then
MsgBox “The cell value is a number! “ & ActiveCell.Value
ElseIf IsDate(ActiveCell) Then
MsgBox “The cell value is a date” & ActiveCell.Value
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
Sub Check_cell_value_2()
If IsNumeric(ActiveCell) And ActiveCell <> “” Then
Inhalt = “The cell value is a number!”
ElseIf IsDate(ActiveCell) Then
Inhalt = “The cell value is a date!”
ElseIf ActiveCell <> “” Then
Inhalt = “The cell value is a text!”
ElseIf ActiveCell = “” Then
Inhalt = “The current cell is empty!”
End If
MsgBox Inhalt & ActiveCell.Value
End Sub
Sub Practical_Example()
intInput = InputBox(“Please enter your number!”)
If IsNumeric(intInput) = True Then
If intInput < 5 Then
a=2
b=3
ElseIf intInput > 5 And intInput < 10 Then
a=4
b=5
ElseIf intInput > 10 And intInput < 15 Then
a=6
b=7
End If
Else
MsgBox (“Please enter your number!”)
Exit Sub
End If
intResult = a * b
MsgBox intResult
End Sub
Sub Select_Case_statement_I()
grade=InputBox(“Well, what grade did you get?“)
Select Case grade
Case 1
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have
fun!“
Case 2
MsgBox “Great. Here is your movie ticket with popcorn. Have fun!“
Case 3
MsgBox “Good, here is your movie ticket. Have fun!“
Case 4
MsgBox “Alright. Exceptionally done. Here is your movie ticket! “
Case >= 5
MsgBox “You should still learn. Sorry! “
End Select
End Sub
Sub Select_Case_Anweisung_II()
grade =InputBox(“Well, what grade did you get?“)
Select Case grade
Case 1 To 2
MsgBox “Great. Here is your movie ticket with popcorn and ice cream. Have
fun!“
Case 3 To 4
MsgBox “Good, here is your movie ticket. Have fun!“
Case >= 4
MsgBox “You should still learn. Sorry! “
Case ““
MsgBox “If you do not enter a grade, you will not get a movie ticket!“
End Select
End Sub
6.2 Loops
A loop is a framework which repeats a certain part of the program several
times. The loop part in a procedure is as specified unless another condition is
fulfilled. A distinction is made between pre- and post-tested loops. That is,
whether the check condition is in the loop head or loop foot of the repeat
mechanism.
The loop can be terminated prematurely when entering certain state with the
exit statement.
For...Next statement
While…Wend statement
Do...Loop statement
In the following example, the counter “i” through 8 is run through. After each
run, the counter increases by the value 1. So i = i + 1.
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.
Now a combination with If...Then...Else decisions. The run in the lower
example runs with three steps backward and is conditionally terminated
prematurely. Once the value i is less than 3, exit with Exit For before
appearing in the immediate area. So, i = i – 3.
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 contained “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.
The first value in parenthesis of the Cells statement indicates the row and the
second value indicates the column. In our example, “x” is incremented by “1”
after each pass, starting at “1”. The second value does not change, it remains
at “1”, i.e. the column “A”. In addition, we are rebuilding the If...Then...Else
decision here. Once the cell to be read is empty, our loop is terminated.
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.
.
.
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
.
This loop repeats instructions for all elements of a data field with the number
of passes equaling the number of elements.
I think two examples suffice. We will use For Each..Next statement a bit more
later on.
In the example below, all sheets (tables, charts, etc.) are output.
While
Until
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.
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
Do While Range(“A” & i) <> “Wheel”
Debug.Print Range(“A” & i)
i=i+1
Loop
Debug.Print Range(“A” & i). Value & “Found in cell: “ & Range(“A” &
i).Address
End Sub
Sub DoWhileLoop_statement_2()
i=1
Do While Range(“A” & i) <> “”
Debug.Print Range(“A” & i)
i=i+1
Loop
Debug.Print “Next empty cell is in: “ & Range(“A” & i).Address
End Sub
Figure 60: Suchen_2 Do...Loop
The next two examples are with the Do ... Until ... Loop statement. The result
of this statement is the same as before. The difference next to the Until
statement is the operator. Here an equal sign (=) is used instead of “Smaller
(<) and Larger (>)” characters.
Sub DoUntilLoop_statement_1()
i=1
Do Until Range(“A” & i) = “Rad”
Debug.Print Range(“A” & i)
i=i+1
Loop
Debug.Print “Found in cell: “ & Range(“A” & i).Address
End Sub
Figure 61: Search with Do...Until_1
Sub DoUntilLoop_statement_2()
i=1
Do Until Range(“A” & i) = “”
Debug.Print Range(“A” & i)
i=i+1
Loop
Debug.Print “Next empty cell is in: “ & Range(“A” & i).Address
End Sub
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
The With statement can combine multiple statements for a given object. It
brings us two important benefits:
1. Less paperwork
Between the With and End With statements we first define “where”, then
“what” and “how” to display or format. For example, in “cell”, “font” should
be displayed in bold.
All items that were not changed during recording are recorded as “False” or
“0”. These can be easily removed. Stacking the With statements minimizes the
listing by a few lines.
In the second example, the column and the row of the active cell are set to the
optimal height or width.
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:
GoTo or GoSub…Return.
With this statement, our macro continues from the specified line. This line is
terminated with a colon “:”. For example, “Note_2_3:” And this line is then
justified to the left in our listing.
Sub GoTo_Examplel()
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
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 hom.
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” or “6”, then “GoSub Number”
will be executed. If it is “content = 3”, then “GoSub number_3” will be
executed, if “content = rt”, then “GoSub Text” is executed.
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
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 continue.
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.
Now “Cancel” comes into play. If there are two buttons, we have to add the
clicked button to a value. The example “Msgbox_2_1” with a constant and the
example “Msgbox_2_2” with the value of a constant. Both have the same
result.
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.
Sub Break_up_or_concatenate()
strFirstName = “Harun,”
‘Result in MsgBox
MsgBox “Hello “ & strFirstName & vbLf & vbLf & _
“Congratulations to your first child.” & Chr(10) & _
Chr(10) & vbCr & _
End Sub
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.
Sub MsgBox_Symbol()
MsgBox “That’s a stop mark.”, vbCritical
MsgBox “That’s a question mark.”, vbQuestion
MsgBox “That’s an exclamation mark.”, vbExclamation
MsgBox “That’s an information mark.”, vbInformation
End Sub
Sub MsgBox_SystemModal()
MsgBox “I stay in sight until you read me.” & vbLf & _
“If you also change your application, I’m still there!”, _
vbOKOnly Or vbSystemModal, “I have to read that!”
End Sub
Figure 77: An example with vbSystemModal
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:
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.
End Sub
Figure 79: MsgBox with more InputBox
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
Bibliography
Online Microsoft Developer Network
https://docs.microsoft.com/de-DE/office/vba/api/overview/