Sie sind auf Seite 1von 38

Notes on Excel Macros

From:

Jrgen Kozlik

Subject:

Notes on Excel Macros

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

Working with Objects.........................................................................15

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

Notes on Excel Macros

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

Select One File......................................................................................30


Select One or More Files..........................................................................31

9 New Excel Functions..............................................................................32


10 Command Buttons and other Controls........................................................33
10.1 Useful Controls.................................................................................33
10.2 Design Mode....................................................................................33
10.3 Important Properties of Controls...........................................................34
11 Excel and Other Microsoft Applications......................................................35
11.1 Including Libraries.............................................................................35
11.2 Make Excel Send A Mail with MS Outlook..................................................36
12 Useful Tips..........................................................................................37
12.1 Optimizing For Speed.........................................................................37
12.2 Date and Time..................................................................................37
12.2.1 Hardcoded (Frozen Time).........................................................................37
12.2.2 Live (Current Time)................................................................................38

12.3 Your Code Doesn't Start?......................................................................38

Page 2 of 38

Notes on Excel Macros

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

Notes on Excel Macros

Four levels of security are defined:

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

Notes on Excel Macros

When opening an Excel file that contains macros, you may be prompted whether you want
to activate them:

Page 5 of 38

Notes on Excel Macros

How to Record a Macro

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

3. Perform the actions that you want to record

Page 6 of 38

Notes on Excel Macros

4. Stop recording (Developer Stop Recording)

Now the actions have been saved into a macro.

Page 7 of 38

Notes on Excel Macros

How to Run a Macro

3.1

Run from the List of Macros

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

Notes on Excel Macros

3.2

Allocating a Keyboard Shortcut to a Macro

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.

No digits are allowed, only letters, but these are case-sensitive.


Some keyboard shortcuts are already taken for something else, like Ctrl-A, Ctrl-O, Ctrl-S,
Ctrl-W (try this!)
Hint: It is safer to use Ctrl-Shift-Letter.
Once the shortcut is defined, you can run your macro right from the keyboard.

Page 9 of 38

Notes on Excel Macros

3.3

Allocating an Icon or a Menu in a Toolbar to a Macro

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

Notes on Excel Macros

Page 11 of 38

Notes on Excel Macros

The VBA Editor

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 Watches Window shows the values of watched variables.

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.

The display of the windows is controlled with the View menu.

Page 12 of 38

Notes on Excel Macros

Coding

5.1

Writing Clean Code

Comments start with an apostroph. The rest of the line is ignored.


' This macro does the following: ....
Dim D as Integer, M as Integer, Y as Integer ' day, month and year of each purchase

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

16-bit signed integer

Long

32-bit signed integer

Single

32-bit float

Double

64-bit float

Date

float value, counting days

String

variable length

Object

address of an object

Variant

any of the above

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

Notes on Excel Macros

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

The active workbook (Excel file) can be addressed with ActiveWorkbook.

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

The active sheet can be addressed with ActiveSheet.

Page 14 of 38

Notes on Excel Macros

5.3.3

A Range of Cells

One cell by address: Range("B6")


Several non-adjacent cells together by address: Range("B6, C8")
A rectangle, by address of top-left and bottom-right cell: Range("C3:D4") or
Range("C3", "D4").
One row: Rows(6)
One or several rows: Rows ("6:8")
One column: Columns(5) (selecting column E)
One or several columns: Columns("Q:S")
All cells: Cells

5.3.4

A Single Cell

A cells by row and column: Cells(5,1) will address cell A5


The active cells can be addressed with ActiveCell.
A cell relative to the active cell: ActiveCell.Offset(1, 2) will address cell C6, when
cell A5 was active (one row down, two columns right).

5.4

Working with Objects

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

Clear the selection

Selection.ClearContents

Delete current line

Selection.Delete Shift:=xlUp

Adjust width of all


columns

Columns.AutoFit

Remark
lines below are shifted up

Page 15 of 38

Notes on Excel Macros

5.4.3

Properties

Most properties of an object can be read and written.


Property

Code

Name of the current Excel


file

ThisWorkbook.Name

Value of the active cell

ActiveCell.Value

Font size of the current


selection

Selection.Font.Size

Set text colour of cell B4 to


red

Cells(4,2).Font.ColorIndex = 3

ColorIndex values range


from 0 to 56

Set background colour of


cell B4 to yellow

Cells(4,2).Interior.ColorIndex
= 6

ColorIndex values range


from 0 to 56

Set background colour of


cell B4 to orange

Cells(4,2).Interior.Color =
RGB(255,153,0)

The three parameters of


the RGB function are the
intensities of red, green
and blue, ranging from 0
to 255

Display values in column D


with three decimals

Columns("D").NumberFormat =
"0.000"

Cell C7 shall always show


the current date

Range("C7").Formula =
"=TODAY()"

Date of last recalculation,


time is midnight.

Formula relative to the


active cell

ActiveCell.Formula = "= RC[1]+1"

When the active cell is B5,


the formula will be
"=A5+1" (same row, one
column to the left)

5.5

Loops

5.5.1

Loop UNTIL Condition Is True

Remark

' Looking for first empty cell in column A


Z = 0
Do
Z = Z + 1
Loop Until Cells(Z, 1).Value = ""

5.5.2

Loop WHILE Condition Is True

' Looking for first non-empty cell in column A


Z = 1
Do While Cells(Z, 1).Value = ""
Z = Z + 1
Loop

Also possible with WHILE-WEND:


While Cells(Z, 1).Value = ""
Z = Z + 1
Wend

Page 16 of 38

Notes on Excel Macros

5.5.3

Loop Over Fixed Number of Elements

YearSum =0
For Month = 1 To 12
YearSum = YearSum + MonthSum(Month)
Next

5.5.4

Loop Over All Elements of a Set

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

Getting Out of Endless Loops

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

One condition, one action:


If Alpha < 0 Then Alpha = Alpha + 360

Page 17 of 38

Notes on Excel Macros

5.6.2

If Then Else (Elseif)

One condition, two different actions:


If P <> 0 Then
Cells(2, 5).Value = 1 / P
Else
Cells(2, 5).Value = "cannot calculate value"
End If

Several conditions with one action each:


If A > A_Max Then
Status = "A is too high"
ElseIf B > B_Max Then
Status = "B is too high"
Else
Status = "A and B are okay"
End If

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

Note the point at the start of the line.

Page 18 of 38

Notes on Excel Macros

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 divide by a number and it happens to be zero.

The user is prompted for a text, but he enters an empty string.

You check all Excel lines, but you reach line 65535 before your condition is met.

You want to open a file, but it doesn't exist.

This year is a leap year, so there is a February 29th.

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

Error Handling Routine

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

Notes on Excel Macros

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

Notes on Excel Macros

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 in the VB editor with the menu "Debug Step Into"

Or by pressing "F8".

Page 21 of 38

Notes on Excel Macros

The following shortcuts can be used:

6.2

Key

Action

F8

Single Step

Shift-F8

Step over this subroutine

Ctrl-Shift-F8

Step out of the current routine

Ctrl-F8

Run until cursor

F5

Run until end (or next breakpoint, see chapter 6.2)

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

Notes on Excel Macros

6.3

Checking the Values of Variables

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 Immediate Window, print out the variable


print Y
Or
? Y

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

Notes on Excel Macros

Watches can be displayed in the "Watches" window of the editor. At any break, all watched
variables and their values are displayed.

Hint: Watches slow the program down. Use only if necessary.

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

Notes on Excel Macros

User Input/Output

7.1

User Input

The InputBox can be used to request input from the user:


SearchItem = InputBox("What are you looking for?", "A question")

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

Messages to the User

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

Decision = MsgBox("Do you really want to delete the data?", _


vbYesNo + vbQuestion, "Be careful!")

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

Notes on Excel Macros

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

First group: buttons


vbOKOnly

Display OK button only

vbOKCancel

Display OK and Cancel buttons

vbAbortRetryIgnore

Display Abort, Retry, and Ignore buttons

vbYesNoCancel

Display Yes, No, and Cancel buttons

vbYesNo

Display Yes and No buttons

vbRetryCancel

Display Retry and Cancel buttons

Second group: icons


vbCritical

16

Display Critical Message icon

vbQuestion

32

Display Warning Query icon

vbExclamation

48

Display Warning Message icon

vbInformation

64

Display Information Message icon

Third group: default button


vbDefaultButton1

First button is default

vbDefaultButton2

256

Second button is default

vbDefaultButton3

512

Third button is default

vbDefaultButton4

768

Fourth button is default (if a Help button


is used, which I will not describe here)
Return Codes

vbOK

"OK" selected

vbCancel

Cancel

vbAbort

Abort

vbRetry

Retry

vbIgnore

Ignore

vbYes

Yes

vbNo

No

Page 26 of 38

Notes on Excel Macros

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

Please note that the return value is an integer.

Page 27 of 38

Notes on Excel Macros

File Input/Output

8.1

Writing to a Text File

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

Don't forget to close the file after you finished writing.

8.2

Reading from a Text File

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

Don't forget to close the file after you finished reading.

Page 28 of 38

Notes on Excel Macros

8.3

Importing a Text File into Excel

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:

In VBA, the code would look somewhat like this:


Workbooks.OpenText Filename:="C:\Temp\testfile.txt", Origin:=xlMSDOS, _
StartRow:=1, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, Comma:=True, Space:=False, Other:=False

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

Notes on Excel Macros

8.4

Using a File Dialog

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

Select One File

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

Notes on Excel Macros

8.4.2

Select One or More Files

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

Notes on Excel Macros

New Excel Functions

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

Notes on Excel Macros

10

Command Buttons and other Controls

10.1

Useful Controls

"Controls" are among others:


Control

Appearance

Remarks

Command Button

Used to launch macros

Spin Button

Used to increment or
decrement the value of
the linked cell

Scroll Bar

Used to change the value


of a cell over a large range

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

Notes on Excel Macros

10.3

Important Properties of Controls

Whether it is a control box, a spin button, a scroll bar, look at:


Property

Meaning

Height/Width

Size of control

Top/Left

Position of control

Visible

Determines whether control is displayed or not

Enabled

Determines whether control will have an effect or not

Caption

Text of control button

BackColor, ForeColor

Color of background and foreground

Picture

Background picture of control button

Accelerator

Key that has to be pressed together with "Alt" in order to


access control

Linked cell

Cell to which control is linked (for scroll bar, spin


button, check box etc.)

SmallChange,
LargeChange

Step sizes for spin buttons (only small change) and scroll
bars

Min, Max

Smallest and largest possible values for scroll bar and


spin button

Page 34 of 38

Notes on Excel Macros

11

Excel and Other Microsoft Applications

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

Notes on Excel Macros

11.2

Make Excel Send A Mail with MS Outlook

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

Notes on Excel Macros

12

Useful Tips

12.1

Optimizing For Speed

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

Date and Time

12.2.1

Hardcoded (Frozen Time)

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

Notes on Excel Macros

12.2.2

Live (Current Time)

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

This can be used in debug prints:


Debug.Print Time, "------- START -------"

12.3

Your Code Doesn't Start?

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

Das könnte Ihnen auch gefallen