0% found this document useful (0 votes)
90 views

Excel VBA - Easy and Fast Start With Simple Examples - Intermediate - S Guide To Learn VBA Programming Step by Step An Introduction To Excel Programming

Uploaded by

Arpan Sen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Excel VBA - Easy and Fast Start With Simple Examples - Intermediate - S Guide To Learn VBA Programming Step by Step An Introduction To Excel Programming

Uploaded by

Arpan Sen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

EXCEL

VBA

Easy & Fast Start


With Simple Examples
Copyright © 2021
Niclas Wittner
Alle Rechte vorbehalten.
ISBN:
9798738001017

Content
Introduction
Applying Excel Macro Examples
Add Developer Tab
Basics
How to run a macro
Macro Examples of Excel
Show worksheets
Hide worksheets down to the Active Sheet
Delete worksheets Except for the Active Sheet
Add worksheets
Sort worksheets alphabetically
Protect worksheets
Remove Sheet protection
Open calculator
Find the number of formulas in workbook
Show rows and columns
Unconnect cells
Save workbooks with timestamps in the name
Save each worksheet as a separate PDF
Convert formulas to values
Protecting/locking cells with formulas
Insert a row after each other row in the selection
Set time stamp in cell
Update pivot tables in the workbook
Highlight all cells with comments
Sort data by multiple columns
Find numeric part from a string
Find text from a string
Remove special characters from a string
Find the last filled row
Find the last filled column
Password Generator
Custom Menu
Introduction
With the application of Excel macros, the work can be much faster and save
you a lot of time.
One way the VBA code can be generated is by recording the macro. This
code, which is created via the macro recorder, can be used. However, this has
the disadvantage that much more code is generated that is not needed.
Therefore, it is worth having a collection of useful VBA macro codes that
you can apply and run at any time.
Of course, at the beginning the effort is higher to create such an Excel VBA
code, because it can take some time. But the nice thing about it is that once
the code is written, the work can be done more automatically and faster.
In this little guide you will get some useful Excel macro examples that you
can use in your everyday life. You will enjoy these codes as you will make
your life easier. This gives you access to this collection of Excel VBA codes
at any time.
Before I go into the individual macro examples and show you how to include
these macros in custom menus, I'll give you a few little basics and show you
how to use these sample codes.
Applying Excel Macro Examples
To use the code from one of the examples, you must follow these steps:
Open the Excel workbook where you want to use the macro.
Press and hold the ALT key and press F11. This shortcut opens the VB
editor.
Right-click one of the objects in Project Explorer.
Go to Insert and select Module
Then copy and paste the code into the module code window (yellow area
marked).

In most cases, the codes can be copied into the module block. However, some
codes may also belong in the worksheet code window. In this case, double-
click the worksheet object and copy the code to the code window.
After you successfully insert the code into the workbook, this folder must still
be saved as .xlsm.
Add Developer Tab
If the Developer tab is not already included in the ribbon, you have to do the
following:
Click with the right-mouse button in the ribbon bar.
Another window appears. There you have to click on "Customize ribbon...".

Now you are in the Excel options.


There you go to the right side of "Main Tabs" via "Customize the ribbon".
You select "Developer" by check mark and then click OK.
Basics
In this section you will learn some basics/concepts of the VBA.
Macro
A summary of multiple commands can be called a macro. These commands
can be called together. These were originally small work aids, but now a few
tens of thousands of lines of code can be generated. This means that with
increasing experience, the possibilities are unlimited for you as well.
Module
A module is a container. This container is for codes and variables. The codes
can be functions, so values are returned or macros, these do not return values.
Thus, a module stores a container of VBA routines attached to a workbook.
Procedure
In the VBA, the procedure is the generic term for functions and subprograms.
The procedure is defined by an initial declaration statement (sub or function)
and an end statement with statements in between.
Comments
If you encounter the comment symbol (') in a code example, the following
text is a comment, so the Visual Basic Compiler knows that this text can be
ignored. Comments are brief, explanatory notes. These serve for better
comprehensibility.
Comments can be inserted on the same line after a statement or occupy an
entire line.
Keywords
Keywords are reserved words that cannot be used as identifier names. Here is
a list of VBA keywords:
#If CInt DefLngLng For Mod RSet
#Else CLng DefLngPtr Friend New Select
#Else If ClngLng DefObj Function Next Set
#End If ClngPtr DefSng Get Not Single
#Const Compare DefStr Global Nothing Static
Alias Const Dim GoTo Null Step
And CSng Do If Object Stop
As CStr Double IIf On String
Base Currency Each Implements Option Sub
Boolean CVar Else Integer Optional Text
Byte Datebase Elseif Is Or Then
ByRef Date Empty Let ParamArray To
ByVal Declare End LBound Preserve True
Call Defbool Enum Lib Private Type
Case DefByte Erase Like Property TypeOf
CBool DefDate Error Long Public Ubound
CByte DefDec Event LongLong RaiseEvent Until
CCur DefDouble Exit Loop ReDim Variant
CDate DefInt Explicit LSet Resume Wend
CDbl DefLng False Me Return While
With WithEvents

Data Types
A data type indicates how large a variable is and what can be stored in it.
Imagine a shelf, this is the main computer memory. The shelf has many
different drawers. Each drawer has different shapes and sizes. And each
drawer in itself corresponds to a data type
VBA has numeric and non-numeric data types.
The following table shows the available numeric data types:
Datatype Range
Byte 0 bis 255
Integer 32.768 bis 32.767
Long -2.147.483.648 bis 2.147.483.647
Single -3,402823E+38 bis -1,401298E-45 for negative Values
1,401298E-45 bis 3,402823E+38 for positive Values
Double -1,79769313486231E+308 to
-4,94065645841247E-324 for negative Values
4,94065645841247E-324 to
1,79769313486232E+308 for positive Values
Decimal +/-79.228.162.514.264.337.593.543.950.335 without decimal
point
+/-7,9228162514264337593543950335 with 28 Decimal
places; the smallest number is nonzero
+/-0,0000000000000000000000000001
Currency -922.337.203.685.477,5808 bis 922.337.203.685.477,5807

The following table shows the available non-numeric data types.


Datatype Range
String 0 to 2 Billion (variable length)
1 to 65.400 (fixed length)
Boolean True or False
Date 1. January 100 to 31. December 9999
Object Any reference to an Object object
Variant Numeric values in the range of the Double data type
As with variable-length string
Variables and constant
One of the most important components of a programming language is the
variables and constants.
The variable is a space for information in the computer's main memory. In
order to be able to address the variable with our commands and instructions,
it gets a name. By declaring the variables, it can accommodate certain
quantities and content.
A constant is a special form of the variable. The contents of a constant are set
once and then remain unchanged. Constants must also be declared with a data
type and have their own name. An example of such a constant can be sales
tax.
Operator
Operators are at the heart of any calculation. They are the characters we use
to compare for example values.
The following operators are available:

arithmetic operators
comparison operators
logical operators and
concatenation operators

Arithmetic operators
Arithmetic operators are used to perform mathematical /arithmetic operations
such as addition, division, multiplication, etc.
Operator Designation Example Explanation
+ Plus a+b Returns the sum of the operands
- Minus a-b Returns the difference between the operands
* Multiplication a*b Returns the product of the operands
/ Division a/b Returns the quotient of the operands
Mod Modulo A Mod b Returns the remainder of an integer division of
two numbers
^ Exponent a^b Raises a number to the power of another number

Comparison
Operator Designation Example Explanation
= equal a=b True, if the values of the operands are the same,
otherwise False
<> unequal a<>b True, if the values of the operands are not the
same, otherwise False
< smaler a<b True, if the value of the left operand is less than
that of the right operand, otherwise False
> bigger a>b True, if the value of the left operand is greater
than that of the right operand, otherwise False
<= equal to or less a<=b True, if the value of the left operand is less than
or equal to that of the right operand, otherwise
False
>= greater or equal a>=b True, if the value of the left operand is greater
than or equal to that of the right operand,
otherwise False

logisch Operatoren
Operator Example Explanation
And a and b Compares both expressions, returns True when both expressions
are evaluated as True, otherwise False
Or a or b Compares both expressions, returns True when both expressions
are evaluated as True, otherwise False
Not Not a If the specified expression is True, the operator inverts it to
False. (Vice-versa)
Xor a Xor b Returns True only if one of the specified expressions is True,
otherwise False

Concatenate operators
For strings, there are the concatenation operators, namely + and &.
If one of the two operands is a string, it does not matter whether you use + or
& , the result is always a concatenation.
However, if the operands are numbers, + is interpreted as an addition, and &
as a concatenation.
That's why it makes sense to always use that & for concatenation.
An Example:
How to run a macro
Here are the steps to run a macro after you successfully copy the code to the
VB editor:
Go to the Developer tab and click Macros.

The Macro dialog box shows you all the macros that are included in this open
workbook.
Now select the macro you want to run.
Then click the Run button.
The basis has now been created. Now we can dive into the world of macros
and discuss the useful macro examples. With these examples, you can
automate many work steps and thus save a lot of time.
Macro Examples of Excel
The following list of some useful codes that can make your day-to-day work
easier and thus speed up some processes and workflows.

Show worksheets
Sometimes there are workbooks that contain a lot of worksheets. To keep
track, many of these worksheets are often hidden.
The following macro displays all worksheets in the corresponding workbook
with one click

The VBA loop (For Each) loops over each worksheet and sets the Visible
property of the respective sheet to True and thus to Visible.
Hide worksheets down to the Active Sheet
If a workbook contains a worksheet that is displayed as a dashboard/report,
and all other worksheets have the function of populating that dashboard but
otherwise need not be displayed, they can be hidden with the following code.
Delete worksheets Except for the Active Sheet
If you have a workbook that contains a lot of worksheets that are no longer
needed, you can delete those sheets with this code. The active Sheet will not
be deleted.

Add worksheets
You can use an input box to specify how many worksheets to add to this
workbook.
If you enter a comma number, the macro will interpret the number as an
integer. If you enter 2.38, 2 worksheets are added.
Sort worksheets alphabetically
Workbooks that contain many worksheets can be sorted alphabetically using
this VBA code. This can be the case if an employee is stored with his data per
worksheet and the worksheet name is equal to the employee name.
Or, behind each sheet, there is a product so that the worksheet names are
labeled with the product names.

The Application.ScreenUpdating property can be used to refresh the display


from Excel.
False prevents the screen from flickering and significantly increases the speed
of execution.
Protect worksheets
This code can be used to protect all worksheets.
The password is entered within the code. This password is also required to
remove the protecter of the worksheets.

Remove Sheet protection


With a simple adjustment (marked in yellow) of the previous code, you can
use this code to give up protection on all sheets.
Note: The password must be the same as the password used to protect the
sheets. If the same password is not used, you will see run-time error '1004'.

Open calculator
If you have a Windows computer, you can use this code to open the
Wondows calculator from Excel. This VBA code only works with Windows,
if you want to run it with the MAC version, you will receive an error
message.

Find the number of formulas in workbook


Use this code to determine the number of formulas in the entire workbook.
The result is output in an Msgbox.
Show rows and columns
This code displays all rows and columns

Unconnect cells
If a worksheet has merged cells, the data cannot be sorted. In this case, a
macro helps to remove all connected cells.

Save workbooks with timestamps in the name


When working in projects, Excel is often an important medium. Several
versions of an Excel workbook are often created during the course of the
project. A good way to save different working versions is with a timestamp in
the name of the file.
This allows you to return to a specific file to see what changes have been
made or what data has been used.
Below is the code that automatically saves the workbook to the specified
folder and adds a timestamp when it is saved.

In this code, you must specify the location of the folder and the file name.
That is, "PFAD AND FILENAME" must be replaced with the location and
file name.
Save each worksheet as a separate PDF
If you are working with a large number of data stored in different worksheets
(example.: worksheet per product, per department, per g/l account group, and
so on), you may need to save it as separate PDF files.
It can be a time-consuming process if you want to manually save the
worksheets as PDF. VBA can speed this up a lot.
Here is a VBA code that saves each worksheet as a separate PDF.

In this example, " C:\PATH" must be replaced with the correct path.
Convert formulas to values
If you have a worksheet with a lot of formulas and you want to store them as
fixed values, then this code is just the right one.

This code automatically identifies the cells used and converts them as values
accordingly.

Protecting/locking cells with formulas


For worksheets that contain a lot of calculations/formulas, it sometimes
makes sense to lock them against accidental deletion or modification.
You can use this code to lock the cells with formulas so that they can no
longer be changed. The other cells are not locked.

Insert a row after each other row in the selection


Use this code if you want to insert a blank line after each line in the selected
range.
You can also customize this code to insert an empty column after each
column in the selected range.
Set time stamp in cell
Timestamps are often used when certain activities are to be tracked.
This may be the case if you want to see, for example:
• when the report was last updated
• when data was entered in a cell
• when a sales invoice was created
• etc.
When an entry is made or the existing content is edited, the VBA code can
display this change through a date and time stamp.
This example sets a timestamp in column B if an entry has occurred in a cell
in column A.
Note: This code must be inserted into the worksheet code window. All other
codes have been stored in the code window in the module.
For this example, double-click the VB editor on the sheet name for which
you want to use this functionality. Then copy code into the code window of
this sheet.

Furthermore, this code refers to column A. If a data entry occurs in column A


(Target.Column = 1), a date and time stamp is inserted in column B in the
corresponding row. You can customize this to suit your needs.
Update pivot tables in the workbook
This code allows you to update multiple pivot tables on a worksheet at the
same time.

Highlight all cells with comments


All annotated cells can be highlighted with the following code.

In this case, the Green cell is highlighted. You can customize this to suit your
color preferences.
Sort data by multiple columns
Suppose you have a file that looks like this:
Below is the code that sorts the data based on multiple columns:

Note: In this code, you first ascend by column A, then sort by column B
ascending.
The result for this example is as follows:
Es werden drei wichtige Parameter verwendet:
Key: gibt an, was die Basis für die Sortierung ist. In dem
Beispiel ist es die Spalte A und die Spalte B
Order: gibt an, ob die Daten aufsteigend oder absteigend sortiert
werden sollen. In diesem Beispiel werden die Daten aufsteigend
sortiert
Header: gibt an, ob der Bereich eine Überschriftzeile hat. Wenn
ja, wird dieser bei der Sortierung ausgeschlossen. In diesem
Beispiel gibt es eine Überschriftzeile

Three important parameters are used:


Key: indicates what is the basis for sorting. In the example, it is
column A and column B
Order: indicates whether the data should be sorted in ascending
or descending order. this example sorts the data ascending
Header: indicates whether the range has a heading line. If so, this
is excluded during sorting. In this example there is a heading line
Find numeric part from a string
If you need only the numeric part or only the body part from a string, you can
create it with a custom function in VBA.
You can use this function on the worksheet like a normal Excel function.
This function extracts the numeric or text part from the string.

The VBA code is a function for extracting a numeric part from a string.
The function must be placed in a module so that it can then be called up in
the worksheet with the function = Numeric.
This function takes only one argument, that is, the cell reference of the cell
from which you want to retrieve the numeric part.

Find text from a string


Remove special characters from a string
This code is also a function that can be called within Excel. The following
characters will be removed: "-.,:;+ß'*?=)(/&%'!'][""
You can remove characters or add any character in the place "Const special
character as String =".
Find the last filled row
This code can be used to quickly determine the last filled line.
Find the last filled column
This code can be used to quickly determine the last filled column. This
example finds the column for the first row. The column number and column
letter are not displayed.
Password Generator
In this day and age, a life without passwords is unthinkable.
You will also know this if you need a new password again and you can't think
of any ad hoc.
Then I have the perfect solution for them. The self-created password
generator.
With this generator you can generate a 10-digit password.

Rnd: With the Rnd function, random numbers from 0 to 1 are generated from
the set of real numbers.
Chr: The Chr function returns the ASCII string to the specified number.
Rnd * 90: Damit werden Zufallszahlen zwischen 0 und 90 erzeugt.
If you need a password with more than 10 digits, you can easily adjust the
program to the desired number of digits. This is what you do in the For
statement.
For zeichen = 2 To X
With X you can specify how many characters you want the password to have.

With these Excel macro codes, you can use some tasks in your daily work to
automate tasks and processes. This allows you to increase your productivity
and work more efficiently.
Custom Menu
In the previous section, you learned about some programs that you can easily
integrate and apply.
In this section, I'll show you how to make your programs accessible in the
ribbon. This gives you direct access to your important programs.

Important: The code for creating the menu must be copied to the worksheet
code window.

As you can see, you have a drop-down menu under the "Add-Ins" tab called
"My Programs".
Clicking on "My Programs" lists all the programs you want in this drop-
down.
Currently we see "1st Program - Msgbox". The display of this comes from
the following code block:

In order for a program to run when clicking "1st Program - Msgbox", we


have to create a program in the module.
The name of the program is added in OnAction. In this example, the program
is called Mein_erstes_Programm.
In the module, the program can look like this:

By clicking on "1.Program - Msgbox" the program is called.

A Msgbox appears with the text "This is my first program".

Next, we'll create a program that creates a pivot table. To select it from our
menu, we need to write a block of code that can look like this:
The code must be copied to the worksheet code window.

Now we have the second program selectable in our menu

In order for the program to run, the program must be created in the module.
The program is called "Pivot_erstellen".
We have a table with the tab name "Sales". This has two filled columns.
Column A has the sales and column B has the productIds. Now let's create a
pivot table that shows the sum of sales for each product Ids.
This is what the program can look like.

Clicking on "2nd Program - Create Pivot" creates the pivot table.


Now that the sales totals for each product Ids have been created, we will
create a corresponding chart.
In order for this program to be selectable from our menu, we need to copy the
code block in the worksheet code window.

It is the third program in our menu selectable.

The program for creating the diagram must be stored in the module.
The program may look like this:

The chart is titled „Umsätze“(Sales).


Clicking on "3rd Program - Create Chart" creates the chart.
In the following is our example of the menu, which must be located in the
worksheet code window, so that it can be accessed in the Excel folder when
opening it under Add-Ins. You can customize and expand the program to
your needs at any time.
Here are the three programs that can be accessed from the menu.

With these examples, I want to illustrate how you can easily pack your daily
work routines into programs and make them accessible via custom menus.
Disclaimer

All information in this book has been carefully checked and prepared by the
author. Since errors cannot be excluded, no guarantee can be given for the
validity and correctness.
The author points out that he accepts no liability for any damage or lasting
effects that are directly or indirectly related to the information in this book.
Impressum
© Autor
Niclas Wittner
Kontakt:
Simone Kaiser
Barbarossastraße 25
71332 Waiblingen

You might also like