Excel VBA - Easy and Fast Start With Simple Examples - Intermediate - S Guide To Learn VBA Programming Step by Step An Introduction To Excel Programming
Excel VBA - Easy and Fast Start With Simple Examples - Intermediate - S Guide To Learn VBA Programming Step by Step An Introduction To Excel Programming
VBA
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...".
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
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.
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.
Unconnect cells
If a worksheet has merged cells, the data cannot be sorted. In this case, a
macro helps to remove all connected cells.
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.
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
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.
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:
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.
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.
The program for creating the diagram must be stored in the module.
The program may look like this:
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