Beruflich Dokumente
Kultur Dokumente
From:
Jrgen Kozlik
Subject:
Date:
June 2014
Version:
03.01
Juergen.Kozlik@alcatel-lucent.com
+49 711 821 37695
Abstract:
These are some notes on Excel macros and VB programming that I used for an internal
training. They are based on Excel 2007 in its English version.
The notes are not a complete documentation on Excel and Visual Basic. The reality is much
more complex. Use at own risk. Have fun reading, trying and succeeding.
Comments and corrections are appreciated.
Table of Contents
1
2
3
4
5
Getting Started......................................................................................3
1.1 Developer Menu.................................................................................3
1.2 Security Settings................................................................................3
How to Record a Macro............................................................................6
How to Run a Macro................................................................................8
3.1 Run from the List of Macros...................................................................8
3.2 Allocating a Keyboard Shortcut to a Macro.................................................9
3.3 Allocating an Icon or a Menu in a Toolbar to a Macro...................................10
The VBA Editor.....................................................................................12
Coding................................................................................................13
5.1 Writing Clean Code............................................................................13
5.2 Variables........................................................................................13
5.2.1
5.2.2
Types of Variables..................................................................................13
Declaration of Variables...........................................................................14
5.3
Addressing Objects............................................................................14
5.4
5.5
Loops............................................................................................16
5.3.1
5.3.2
5.3.3
5.3.4
5.4.1
5.4.2
5.4.3
5.5.1
5.5.2
5.5.3
5.5.4
5.5.5
5.5.6
Workbooks...........................................................................................14
Worksheets.......................................................................................... 14
A Range of Cells.....................................................................................15
A Single Cell......................................................................................... 15
Selection............................................................................................. 15
Methods.............................................................................................. 15
Properties............................................................................................ 16
Loop UNTIL Condition Is True.....................................................................16
Loop WHILE Condition Is True.....................................................................16
Loop Over Fixed Number of Elements...........................................................17
Loop Over All Elements of a Set..................................................................17
Exiting Loops........................................................................................17
Getting Out of Endless Loops.....................................................................17
Page 1 of 38
5.6
Conditions......................................................................................17
5.7
5.8
"With" Statement..............................................................................18
Error Handling..................................................................................19
5.6.1
5.6.2
5.6.3
5.8.1
5.8.2
If Then............................................................................................... 17
If Then Else (Elseif)................................................................................18
Select Case..........................................................................................18
Avoiding Errors......................................................................................19
Error Handling Routine.............................................................................19
Debugging...........................................................................................21
6.1 Single-Stepping................................................................................21
6.2 Breakpoints.....................................................................................22
6.3 Checking the Values of Variables............................................................23
6.4 Watch Window.................................................................................23
6.5 Debug Prints....................................................................................24
7 User Input/Output.................................................................................25
7.1 User Input.......................................................................................25
7.2 Messages to the User..........................................................................25
8 File Input/Output..................................................................................28
8.1 Writing to a Text File..........................................................................28
8.2 Reading from a Text File.....................................................................28
8.3 Importing a Text File into Excel.............................................................29
8.4 Using a File Dialog.............................................................................30
8.4.1
8.4.2
Page 2 of 38
Getting Started
1.1
Developer Menu
Many macro actions are accessed over the Develop menu, which is by default inactive. To
activate do the following:
1. Click on the Excel circle in the upper left corner of the Excel window (or type Alt-F)
2. Click on Excel Options
3. Select the third option: Show Developer tab in the Ribbon
1.2
Security Settings
Macros are programs that may do lots of things that you don't expect them to do. Like with
any other program, you shouldn't trust them too much.
Macro Security Settings are in the menu Developer Macro Security:
Page 3 of 38
Hint: Usually, the "Disable all macros with notification" setting is sufficient.
If you open Excel sheets of unknown reliability:
1. Keep with macros disabled (help protect me)
2. Check the macro code whether it seems safe
3. Close the file
4. If the macro code seems safe reopen the file with enabled macros
Page 4 of 38
When opening an Excel file that contains macros, you may be prompted whether you want
to activate them:
Page 5 of 38
This is useful when you have to do the same sequence of actions again and again.
1. Launch the macro recorder (Developer Record Macro)
2. Optionally: define a macro name (default: "Macro" and a number) and/or a shortcut
key.
Hint: use Shift+Letter as a shortcut, in order not to overwrite Excel keyboard
shortcuts like Ctrl-O, Ctrl-P, Ctrl-S...
Page 6 of 38
Page 7 of 38
3.1
The list of macros can be accessed with the menu Developer Macros (or View Macros)
or simply with Alt-F8. Select your macro and click on "Run". The button "Step Into" is good
for debugging.
Page 8 of 38
3.2
If you don't assign a keyboard shortcut during the recording, you can do so later. Open the
list of macros with Alt-F8, pick your macro and click Options.
Page 9 of 38
3.3
For advanced users and their favorite macros, that must always be available:
Use the well hidden button for the Excel Options.
Select the category "Customize", choose commands from Macros, and select those of
your macros that you want to appear in the Quick Access Toolbar. Click Add. Using the
Modify button you can allocate an icon to your macro.
After this, your macro will be available in the Quick Access Toolbar. Unfortunately with
Excel 2007 it is no longer possible to modify the tool bars (now called ribbons).
Page 10 of 38
Page 11 of 38
You don't need always to record actions to create a macro. You can also copy an existing
macro and modify it, or you can write it from scratch. This is done in the VBA editor. The
programming language is called VBA (Visual Basic for Applications).
The VBA Edtitor is launched from Excel or any MS Office application with Start Editor with
"Developer Visual Basic" or simply by typing Alt-F11.
The VBA editor consists of several windows. The most important are:
The Project Window (usually on the left) shows all open Excel files with their
worksheets and their modules. If you need a module for an Excel file, use a rightclick and "Insert Module".
The Code Window shows the code. The current line is marked in yellow, breakpoints
are marked in dark red.
The Immediate Window can be used to type commands directly. It is also used to
display debug.prints
The Call Stack shows which function calls were used to get to the current position
in the code. It can be opened with Ctrl-L and closed with Esc.
The Object Browser shows the available classes, properties, methods etc. that you
can use. It can be opened with F2 and closed with Ctrl-F4.
Page 12 of 38
Coding
5.1
But of course, variables may have names that make comments unnecessary:
Dim DayOfPurchase as Integer, MonthOfPurchase as Integer, YearOfPurchase as Integer
Long program lines can be written over several editor lines. If the last character of a line is
an underscore ("_") it will continue on the next line.
Answer = MsgBox("Do you want to move this line?", _
vbOKCancel + vbExclamation, _
"Be careful!")
Hint: If you write proper comments, you will still understand your code next year. You
don't have ten seconds time to write a comment? Then you will need ten minutes some
time later!
5.2
Variables
5.2.1
Types of Variables
Variables are of different types, which control their value range and the functions you can
use on them.
Important Types:
Type
Description
Implicite Declaration
Boolean
True or False
Integer
Long
Single
32-bit float
Double
64-bit float
Date
String
variable length
Object
address of an object
Variant
Hint: If you use a variable for Excel line numbers, don't use Integer, but Long, because
Integer has a maximum of value of 32767, while Excel line numbers can go up to 65535.
Some operations can use variables of mixed types. You can add an Integer to a single
floating number. You can put an Integer number at the end of a string (for messages like
"Error in line 1").
Page 13 of 38
5.2.2
Declaration of Variables
A declaration of a variable means, that you fix a certain type to a certain variable name. If
you don't do this, the variable will be of the "Variant" type.
Explicit Declaration in the first line of a procedure or a function:
Dim CurrentLine As Integer
Dim Subscriber As Integer
Dim CountryName$
Arrays can be declared, too. The array index starts with 0, if not stated otherwise:
Dim A(100) As Long ' 101 elements from 0 to 100
Dim Monthly_Average(12) as Single ' Index 0 exists, but is probably not used
Dim Yearly_Average(2005 To 2012) ' 8 elements from 2005 to 2012
Hint: Use Option Explicit as the first line in the code, so that accessing any
undeclared variable will cause an error.
Besides the types mentioned in chapter 5.2.1 there are further types that relate to
objects, like Application, File, Range, FileDialog and Sheet.
5.3
Addressing Objects
How objects can be addressed (please note that the plural is used: Sheets, Cells etc.):
5.3.1
Workbooks
5.3.2
Worksheets
Worksheets can be addressed by their name or by their number (in the order they appear,
starting with 1): Sheets("Sheet1") or Sheets(1).
Page 14 of 38
5.3.3
A Range of Cells
5.3.4
A Single Cell
5.4
This chapter gives a few examples what you can do with some objects. Of course there is
much more.
5.4.1
Selection
Once you have selected an object, you can also address it with Selection.
Selection is done by adding .Select to the object, like Sheets("Liste").Select or
Range("E3:E10").Select.
5.4.2
Methods
Action
Code
Selection.ClearContents
Selection.Delete Shift:=xlUp
Columns.AutoFit
Remark
lines below are shifted up
Page 15 of 38
5.4.3
Properties
Code
ThisWorkbook.Name
ActiveCell.Value
Selection.Font.Size
Cells(4,2).Font.ColorIndex = 3
Cells(4,2).Interior.ColorIndex
= 6
Cells(4,2).Interior.Color =
RGB(255,153,0)
Columns("D").NumberFormat =
"0.000"
Range("C7").Formula =
"=TODAY()"
5.5
Loops
5.5.1
Remark
5.5.2
Page 16 of 38
5.5.3
YearSum =0
For Month = 1 To 12
YearSum = YearSum + MonthSum(Month)
Next
5.5.4
Sub ProtectAllSheets()
Dim ThisSheet As Worksheet
For Each ThisSheet In Worksheets
Debug.Print "Protecting worksheet "; ThisSheet.Name
ThisSheet.Protect
Next ThisSheet
End Sub
5.5.5
Exiting Loops
If you need an additional condition to leave the loop, use Exit Do or Exit For:
For Something
some action
If somecondition Then Exit For
some more action
Next
Or
Do While Condition
Some action
If somecondition Then Exit Do
Some more action
Loop
5.5.6
In case you are caught in an endless loop, there are two ways to get out:
1. Press Ctrl-Break (German keyboard: Strg-Pause)
This does not always work!
2. Launch the task manager (Ctrl-Shift-Esc), locate the process EXCEL.EXE and kill it
This will close your Excel worksheets without saving!
Hint: Save your work before running a new macro. If you need to kill Excel, you still have
the last saved version.
Hint: During development, you should save early and save often.
5.6
Conditions
5.6.1
If Then
Page 17 of 38
5.6.2
5.6.3
Select Case
The Select Case Statements checks one variable for different values or ranges. It allows
efficient usage of conditions, because several conditions can be grouped.
Select Case ARFCN
Case 0 To 124, 975 To 1023
DL = UL(ARFCN) + 45
Case 512 To 885
DL = UL(ARFCN) + 95
Case Else
DL = "invalid"
End Select
5.7
"With" Statement
The "With" Statement can be used to write shorter code when several lines refer to the
same object. Instead of
Selection.Font.Name = "Arial"
Selection.Font.FontStyle = "Standard"
Selection.Font.Size = 11
Selection.Font.ColorIndex = xlAutomatic
just write
With Selection.Font
.Name = "Arial"
.FontStyle = "Standard"
.Size = 11
.ColorIndex = xlAutomatic
End With
Page 18 of 38
5.8
Error Handling
5.8.1
Avoiding Errors
Hint: For every line of code that you write, consider what could go wrong
Examples:
You check all Excel lines, but you reach line 65535 before your condition is met.
The obvious way is to check for these error conditions in the code:
If P <> 0 Then
Cells(2, 5).Value = 1 / P
Else
Cells(2, 5).Value = "cannot calculate value"
End If
Or
Do
Product = InputBox("Enter name of product" _
& Chr(13) & "(Line must not be empty)", _
"What are you looking for?")
Loop Until Len(Product) > 0
5.8.2
In some error cases, it is useful to branch to a different part of the code. For this, the On
Error statement can be used. In any case, the Err object is available with its properties
Number and Description.
On Error GoTo 0 will disable specific error handling. Every error is fatal, and will stop
program execution.
On Error GoTo with a line label will specify where to jump to in case of an error. Line
labels consist of a word followed by a colon. The line lable must be in the same function or
subroutine.
On Error Resume Next specifies that in case of error, the next line will be executed.
This is useful if the Err object is checked immediately after a critical operation, where an
error may be caused by run-time environment (File not found and the like).
Page 19 of 38
The following piece of code demonstrates the usage of all three methods:
Public Sub My_Subroutine()
On Error Resume Next
PerformSomeActionWithPotentialError' Critical operation
Select Case Err.Number
Case 0 ' Err.Number = 0 means: no error
Case 429 ' here is a specific error
Err.Clear ' Reset error
TidyUpInCaseOfError
If Err.Number > 0 Then
MsgBox Err.Number & " " & Err.Description
TidyUpInCaseOfError
Exit Sub
End If
Case Else ' Display message box with number and description
MsgBox Err.Number & " " & Err.Description
TidyUpInCaseOfError
Exit Sub
End Select
On Error GoTo Fin ' Now: in case of error goto end of routine
Call DoWhatYouIntendedToDo ' do what is necessary when there is no error
Fin:
TidyUpInCaseOfError
If Err.Number <> 0 Then MsgBox "Fehler: " & _
Err.Number & " " & Err.Description
End Sub
Page 20 of 38
Debugging
6.1
Single-Stepping
You can step through a macro line by line. This can be launched from the list of macros by
selecting "Step Into".
Or by pressing "F8".
Page 21 of 38
6.2
Key
Action
F8
Single Step
Shift-F8
Ctrl-Shift-F8
Ctrl-F8
F5
Breakpoints
You can set breakpoints in the code by clicking into the grey area left of the code or by
typing "F9". When you run the program, it will automatically stop at the breakpoint. You
will be able to check variables or continue by single-stepping.
Breakpoints are cleared the same way as they are set: clicking into the grey area or typing
"F9".
Page 22 of 38
6.3
While you are in single-step mode, you can check the values of variables:
In the Code Window move the mouse over the name of a variable. A yellow balloon
will appear and show its value (mouse is over "Y" in the example below)
In the Watch Window, if you have declared a "watch" (see chapter 6.4)
6.4
Watch Window
If you are interested in the value of a variable during the run of the program, you can
define a watch to watch this variable.
Easiest way to declare a watch: right-click on a variable name in the code window, and
select "Add Watch" from the menu.
Page 23 of 38
Watches can be displayed in the "Watches" window of the editor. At any break, all watched
variables and their values are displayed.
6.5
Debug Prints
You can write debug prints into your code in order to have a trace. Debug prints are
displayed in the Immediate Window.
Debug.Print CurrentValue
Your debug trace is much more readable, if you add a note about what you are printing
out:
Debug.Print "CurrentValue:"; CurrentValue
If you have macros that run for a certain time, it may be a good idea to include a time
stamp in the debug print, so that you know the run time of various parts of your program.
Debug.Print Time; "Start sorting data"
Page 24 of 38
User Input/Output
7.1
User Input
The answer is provided as a string variable, which here is called SearchItem. If the user
clicks on "Cancel" or hits the Esc-key, the variable is empty.
7.2
If you need to give an important message to the user, and maybe ask for a decision, you
can use a message box:
Decision = MsgBox("Conversion finished", vbOKOnly, "Status")
It is obvious that the first parameter is the string that appears in the message box, and the
third parameter is the string in the title bar of the message box.
Page 25 of 38
The second parameter is a numerical value that controls the appearance and behaviour of
the message box. For code clarity it is useful not to use numbers, but the built-in Excel
constants:
Constant
Value
Description
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
16
vbQuestion
32
vbExclamation
48
vbInformation
64
vbDefaultButton2
256
vbDefaultButton3
512
vbDefaultButton4
768
vbOK
"OK" selected
vbCancel
Cancel
vbAbort
Abort
vbRetry
Retry
vbIgnore
Ignore
vbYes
Yes
vbNo
No
Page 26 of 38
Examples:
Decision = MsgBox("Do you really want to delete the data?", _
vbYesNo + vbQuestion, "Be careful!")
If Decision = vbYes Then
...
Endif
Do
Decision = MsgBox("Have you understood?", vbYesNo + vbcritical)
Loop Until Decision = vbYes
Page 27 of 38
File Input/Output
8.1
Text files are opened with a numerical handle (#1 in the example below). The following
example writes the values of the cells B1 to B10 into a file:
Open "C:\Temp\Testfile.txt" For Output As #1
For Z = 1 To 10
Print #1, Cells(Z, 2).Value
Next
Close #1
8.2
Text files are opened with a numerical handle (#1 in the example below). The end of the
file can be checked with the function EOF, with the file handle as parameter.
The statement Line Input reads one complete line from the file (terminated by CR/LF)
and puts it into a string variable.
Open "C:\Temp\Tesfile.txt" For Input As #1
While Not EOF(1)
Line Input #1, strInput
Debug.Print strInput
Wend
Close #1
Page 28 of 38
8.3
With OpenText you may open a text file with Excel as you would do with "File Open" for
a text file with the following import wizard:
This will open the file C:\Temp\ testfile.txt and read tab-delimited data. The file
will be displayed in a new Excel workbook.
Page 29 of 38
8.4
You can use a file dialog to pick one or more files from the file system. A file dialog is an
object that must be declared like a variable, so that you can access its properties. It will
return path and file name together as a string. The desired action (open or save) must be
programmed separately.
8.4.1
To pick one XLS file, the name of which is returned in File1, including path:
Dim fd1 As FileDialog
Dim File1 As String
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.Filters.Add "Excel files", "*.xls"
.AllowMultiSelect = False
.Show
File1 = .SelectedItems(1)
Debug.Print File1
End With
Page 30 of 38
8.4.2
If you want to be able to pick several files, you need to set .AllowMultiSelect to True.
The number of selected files is available in the .Count property. The names of the files
are in the array .SelectedItem.
Dim fd1 As FileDialog
Dim File1 As String
Dim Z As Integer
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.AllowMultiSelect = True
.Show
For Z = 1 To .SelectedItems.Count
File1 = .SelectedItems(Z)
Debug.Print File1
Next Z
End With
Page 31 of 38
You can define your own Excel functions. They can be called like the built-in Excel
functions.
Functions take zero or more input parameters. Their types don't need to be declared.
Functions return exactly one return value. Its type doesn't need to be declared either.
Public Function UL(ARFCN)
Select Case ARFCN
Case 0 To 124
UL = 890 + 0.2 * ARFCN
Case 512 To 885
UL = 1710.2 + 0.2 * (ARFCN - 512)
Case 975 To 1023
UL = 890 + 0.2 * (ARFCN - 1024)
Case Else
UL = "invalid"
End Select
End Function
Public Function DL(ARFCN)
Select Case ARFCN
Case 0 To 124, 975 To 1023
DL = UL(ARFCN) + 45
Case 512 To 885
DL = UL(ARFCN) + 95
Case Else
DL = "invalid"
End Select
End Function
Page 32 of 38
10
10.1
Useful Controls
Appearance
Remarks
Command Button
Spin Button
Used to increment or
decrement the value of
the linked cell
Scroll Bar
Other controls are Check Boxes, Text Boxes, Option Buttons, List Boxs, Combo Boxes and
Toggle Buttons, but their functions can be achieved in Excel with built-in methods. You
don't need a Combo Box when "Data Validation" offers you the same benefit with less
effort.
10.2
Design Mode
In the Developer menu, there is a button to switch the "Design Mode" on and
off:
Once the design mode is on, click on the Insert button and then on the icon of
your desired control. Then draw a rectangle with the mouse on the Excel sheet.
Your desired control will be there, and you can modify its properties.
Page 33 of 38
10.3
Meaning
Height/Width
Size of control
Top/Left
Position of control
Visible
Enabled
Caption
BackColor, ForeColor
Picture
Accelerator
Linked cell
SmallChange,
LargeChange
Step sizes for spin buttons (only small change) and scroll
bars
Min, Max
Page 34 of 38
11
11.1
Including Libraries
You may control other Microsoft applications (Word, Powerpoint, Outlook, ...) from Excel.
It is required to include the other application's objects, so you need to check the
appropriate boxes in the list that you can open with the menu "Tools References".
If you want to address Outlook objects, you need to include the Outlook library:
Page 35 of 38
11.2
You can make excel send a mail using Outlook, where addressee, subject, text etc. can be
constants or may retrieved from Excel cells.
Sub Send_A_Mail()
Dim olApp As Outlook.Application ' This is to open Outlook
Dim olMail As MailItem ' A mail object, of which you can access the properties
Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)
With olMail
.To = "Some.Address@somewhere.xy; Some.Other.Address@somewhere.xy" '
Semicolon to separate addresses
.CC = "Any.Other.Address@somewhere.xy"
.Subject = "Here is the subject"
.Body = "Here is the text"
.Attachments.Add "C:\Temp\testfile.txt" ' This can be done several times
.Display ' This is to display an Outlook window with the mail
.Send ' This will actually send the mail using Outlook
End With
Set olMail = Nothing ' Release the mail item
Set olApp = Nothing ' Release the Outlook application
End Sub
Using such a routine, you can send mails, where the data is taken out of Excel sheets. The
mails will be stored in Outlooks folder as usual.
Hint: Don't abuse this!
Page 36 of 38
12
Useful Tips
12.1
Excel code runs much faster if you switch off time consuming procedures.
After you change the appearance of something, Excel will redraw the screen. You may
want to avoid this and redraw the screen only after all your modifications are finished.
This is controlled with Application.ScreenUpdating.
After you have changed one cell, Excel will recalculate all cells that depend on it. You may
want to avoid this and launch the recalculation only after the modification of all cells is
finished. This is controlled with Application.Calculation.
So at the start of your code you may use:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
But don't forget to return to the previous state before the end of the code:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
12.2
12.2.1
If you need to insert the current date or time as a constant, so that it will not be updated,
you can do the following
Typing Ctrl-; (German keyboard: Strg+Umschaltung-Komma) on the keyboard will put the
current date into the selected Excel cell. The time will be 00:00. This is a constant that
will not be updated.
Typing Ctrl-: (German keyboard: Strg+Umschaltung-Punkt) on the keyboard will put the
current time into the selected Excel cell. The date will be set to Day 0 of Excel's internal
calender (like January 0th, 1900). This is a constant that will not be updated.
The VB code Now will return the current date and time as a constant that will not be
updated:
Cells(18, 1).Value = "Last change by macro:"
Cells(18, 2).Value = Now
Cells(18, 2).NumberFormat = "yyyy-mm-dd hh:mm:ss"
The cell will not be automatically recalculated; it is only changed when the macro runs.
Page 37 of 38
12.2.2
If you need to have the current date and time, and the value shall always be updated when
the sheet is recalculated
Cells(16, 1).Formula = "=NOW()"
In the VB editor, Time is a string that gives you the current time with a precision of 1 s:
print time
15:40:32
12.3
If your code will not start (neither from the Excel sheet nor from the VBA editor), then you
are probably in the break mode (reset state).
This is visible in the title bar of the VBA editor (green arrow).
You need to click on the Reset Button (red arrow) or use the menu "Run Reset" or the
keyboard shortcut"Alt R R"
END OF DOCUMENT
Page 38 of 38