Tải bản đầy đủ (.pdf) (92 trang)

Excel VBA for physicists a primer

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (20.62 MB, 92 trang )


Excel® VBA for Physicists
A Primer



Excel® VBA for Physicists
A Primer
Bernard V Liengme
St Francis Xavier University, Nova Scotia, Canada

Morgan & Claypool Publishers


Copyright ª 2016 Morgan & Claypool Publishers
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system
or transmitted in any form or by any means, electronic, mechanical, photocopying, recording
or otherwise, without the prior permission of the publisher, or as expressly permitted by law or
under terms agreed with the appropriate rights organization. Multiple copying is permitted in
accordance with the terms of licences issued by the Copyright Licensing Agency, the Copyright
Clearance Centre and other reproduction rights organisations.
Rights & Permissions
To obtain permission to re-use copyrighted material from Morgan & Claypool Publishers, please
contact
Online supplementary data files are available at />live/bk978-1-6817-4461-2suppdata.zip
ISBN
ISBN
ISBN

978-1-6817-4461-2 (ebook)
978-1-6817-4460-5 (print)


978-1-6817-4463-6 (mobi)

DOI 10.1088/978-1-6817-4461-2
Version: 20161101
IOP Concise Physics
ISSN 2053-2571 (online)
ISSN 2054-7307 (print)
A Morgan & Claypool publication as part of IOP Concise Physics
Published by Morgan & Claypool Publishers, 40 Oak Drive, San Rafael, CA, 94903 USA
IOP Publishing, Temple Circus, Temple Way, Bristol BS1 6HG, UK


To Pauline, my wife, my friend,
and my amanuensis, with many, many thanks.



Contents
Preface

x

Acknowledgements

xi

Author biography

xii


1

Introduction

1-1

1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11

Preparation
Demonstrating a simple function
Saving a macro-enabled workbook
Using constants and VB functions
User-defined array function
Notes on VBA functions
A simple subroutine
Linking an image to a subroutine
Recording a macro
Finding a home for macros
Typographical matters


2

Variables, Dim statements, and data types

2-1

2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9

Naming variables
The Dim statement
The major reason for variable declarations
Declarations in function headers and for constants
Data types
A second reason for variable declarations
Dimensioning arrays
The Set statement
The With…End With structure

2-1
2-1
2-1
2-3

2-3
2-4
2-4
2-6
2-7

3

Structured programming

3-1

3.1
3.2
3.3

Branching structures (If and Select Case)
Looping structures (For…Next and Do…While/Until)
Some further examples

3-1
3-4
3-7

vii

1-1
1-3
1-5
1-6

1-7
1-8
1-9
1-11
1-11
1-14
1-14


Excel® VBA for Physicists

4

The Excel object model

4.1
4.2
4.3

4.6

Examples of properties, methods and events
The Range object properties
Range object methods
4.3.1 Select, Copy, and Paste
4.3.2 Clear methods
4.3.3 Delete method
WorksheetFunction object
Workbook and worksheet events
4.5.1 Workbook event

4.5.2 Worksheet event
Code for sending email

5

Working with add-ins

5-1

5.1
5.2
5.3
5.4
5.5
5.6
5.7

Creating an add-in
Installation
Using the add-in
Making changes to the add-in
Viewing worksheets
Protecting the add-in
Reversing everything

5-1
5-2
5-2
5-3
5-3

5-4
5-4

6

Numerical integration

6-1

6.1
6.2
6.3
6.4
6.5

The trapezoid approximation
The Simpson 1/3 approximation
An aside
Monte Carlo integration
Gaussian and Romberg integration

6-1
6-4
6-6
6-7
6-8

7

Numerical methods for differential equations


7-1

7.1
7.2
7.3
7.4
7.5
7.6

Euler’s method
The Runge–Kutta fourth-order method
Simultaneous OEDs
Example of a system of two OEDs
Higher order OEDs
R–L circuit

7-1
7-4
7-6
7-6
7-8
7-8

4.4
4.5

4-1

viii


4-1
4-3
4-5
4-5
4-7
4-7
4-7
4-12
4-12
4-13
4-14


Excel® VBA for Physicists

8

Finding roots

8-1

8.1
8.2
8.3
8.4

The bisection method
The successive iteration method
Root finding with Solver

Using range names

8-1
8-3
8-4
8-7

ix


Preface
This work will introduce the reader to Visual Basic for Applications (VBA) and
demonstrate how it can greatly enhance Microsoft Excel® by giving users the ability
to make their own functions that can be used within a worksheet, and to create
subroutines to perform repetitive actions.
Visual Basic (VB, the parent of VBA) has its roots in the educational
programming language BASIC redeveloped at Dartmouth College in 1964. In
the half-century since then, the language has evolved to become a high-powered
object-orientated language which is no longer denigrated by aficionados of
language such as C++ and C#. The VBA compiler and editor is incorporated
within the Excel application; there is nothing to buy or install.
The author’s primary aim is to show the reader how to write both functions and
subroutines, and to demonstrate that this is not a complex topic. The material is
presented in a manner that will allow the reader to experiment with VBA
programming; this is the best way to learn it. The scenarios used in the examples
center around either fairly simple physics or non-complicated mathematics, such as
root finding and numerical integration. The text, therefore, will be suitable not just
for physicists but for other scientists and engineers, including students.
A tested Excel workbook can be downloaded from here for each chapter.
The brevity of the book prevents total rigour so it was necessary to condense some

material, but Internet links are provided so the reader can explore VBA topics in
greater depth. For the reader who prefers a paper reference source, Excel 2007 VBA
by John Green et al (2007, New York: Wiley) is an excellent book, notwithstanding
its date; furthermore, it can be obtained very cheaply online.
The author is more than happy to reply to email inquiries about topics in the
book or other Excel (with or without VBA) questions. Please use the word Excel in
the subject line of each message.
Have fun learning to extend Excel with VBA!
Bernard V Liengme


x


Acknowledgements
The author thanks Microsoft Excel Most Valuable Professionals (MVPs) Jon
Peltier, Bob Umlas, and Jan Karel Pieterse for their help over the years.

xi


Author biography
Bernard V Liengme
Bernard V Liengme attended Imperial College London for his
undergraduate and postgraduate degrees; he held post-doctoral
fellowships at Carnegie-Mellon University and the University of
British Columbia. He has conducted extensive research in surface
chemistry and the Mossbauer effect. He has been at St Francis
Xavier University in Canada since 1968 as a Professor, Associate
Dean, and Registrar, as well as teaching chemistry and computer science. He

currently lectures part-time on business information systems. Bernard is also the
author of other successful books: COBOL by Command (1996), A Guide to
Microsoft Excel for Scientists and Engineers (now in its fourth edition), A Guide to
Microsoft Excel for Business and Management (now in its second edition), Modelling
Physics with Microsoft Excel® (2014), and SMath for Physics: A Primer (2015).

xii


IOP Concise Physics

Excel® VBA for Physicists
A Primer
Bernard V Liengme

Chapter 1
Introduction

Visual Basic for Applications (VBA) is a programming language that has been built
into Microsoft Office since Office 1997. It has its roots in Visual Basic (VB), so when you
perform an internet search on a VBA topic do not be surprised by references to VB.
In this chapter we will make a few simple changes to our Excel environment to
allow us to code and run macros. Then we will see how to code some examples of
simple macros (procedures), i.e. functions and subroutines. We close with a brief
look at recording a subroutine.

1.1 Preparation
There is little to do in preparation. We start by adding the Developer tab to the
Excel ribbon. Right click on the Home tab and select Customize Ribbon. This opens
the dialog box as shown in figure 1.1, click the box to the left of Developer to add a

check mark (if it is not already there), and then click the OK button in the lower
right-hand corner of the dialog. As can be seen from the title in this dialog, one can
also customize the ribbon by using the command File | Options | Customize Ribbon.
The ribbon now has the Developer tab present, as shown in figure 1.2. We can
now check the macro security setting. Open the Developer tab and click on Macro
Security to open the dialog shown in figure 1.3. Make sure that the setting is Disable
all macros with notification (this is the default setting and should not be changed
without good reason.) Beginning with Office 2007, Microsoft required that
workbooks containing macros be saved with the extension XLSM; we refer to
such workbooks as macro-enabled. This is a security feature since a rogue macro can
harm a computer. When you open a macro-enabled workbook you will see a
warning as shown in figure 1.4; click on Enable Content if you trust the workbook
not to have rogue macros. If you are working with Excel 2003, your workbooks will
have the extension XLS even when they contain macros. To learn more about macro
security, visit fice.com/en-us/article/Enable-or-disable-macros-inOffice-files-12B036FD-D140-4E74-B45E-16FED1A7E5C6.
doi:10.1088/978-1-6817-4461-2ch1

1-1

ª Morgan & Claypool Publishers 2016


Excel® VBA for Physicists

Figure 1.1. Customizing the Quick Access Toolbar to add the Developer tab.

Figure 1.2. The ribbon with the Developer tab added.

You may not see this warning every time; Excel seems to remember if a specific
macro-enabled file has been opened in the same user session. At other times the

warning comes with a more ominous message (figure 1.5). It seems odd that this
message occurs when the file sits on the author’s hard drive.
In subsequent chapters all the reader needs to do is open one of the workbooks
(Topic2.xlsm to Topic8.xlsm) which are available for download—see the preface. In
this chapter the reader needs to learn how to open the VB Editor (VBE), add a
module, and save a macro-enabled file. It is best that the reader starts with a new file.
However, to cut down on the work, the companion site has the file Topic1BVL.xlsm,
and this chapter gives instructions on copying from that workbook to the reader’s
new workbook.
1-2


Excel® VBA for Physicists

Figure 1.3. Setting the macro security.

Figure 1.4. Example of a macro warning.

Figure 1.5. Another macro warning format.

1.2 Demonstrating a simple function
Within the Excel environment there are three types of function: the worksheet function
(examples being SUM, AVERAGE, ACOS); VB functions (Lcase, Len, Round);
1-3


Excel® VBA for Physicists

and functions that are coded by a user. Functions of the last type are often referred to
as user-defined functions (UDFs).

Later we will see that all VB functions may be used within a UDF, but there is a
restriction on which worksheet function may be used. In general, if there is an
equivalent VB function then the worksheet function may not be used.
Example. A physics student needs to compute the kinetic energy given the mass and
velocity of the object. Figure 1.6 shows a sample worksheet. In column C he uses a
worksheet formula to compute the kinetic energy, while column D shows how a
UDF may be used. The reader should set up a worksheet like this but leave D2:D5
empty for now. In B7 we have the formula = FORMULATEXT(C2), which displays
the referenced cell’s formula.
Open the Developer tab, click on Visual Basic (the left most icon) to open the
VBE. Figure 1.7 shows the VBE window, but since you have just opened it the
working space (the module area, the panel at top right) will be grey. Click on the
Insert command and select Module. Now type this code into the module:
Function KE(mass, Vel)
KE = (1 / 2) * mass * Vel ^ 2
End Function
You may now return to the worksheet by clicking the green Excel icon on the far
left of the VBE toolbars, or by clicking the worksheet if it is visible behind the VBE.
In D2 type =KE(A2, B2), press Enter to complete the formula, and drag the
formula down to row 5.
Suppose you made a mistake in the code and had entered KE = (1/2)
*mass*vel+2. You can return to the VBE (try the shortcut ALT+F11) and
make the correction. How disappointed will you be when on returning to the
worksheet you find the results in columns C and D still do not agree?
MORAL. Whenever a change is made to a UDF it will not affect the worksheet
until the worksheet is recalculated. Do this by pressing F9, or selecting a cell with the
UDF (D2 for example) and double clicking it.

Figure 1.6. Example of using a UDF.


1-4


Excel® VBA for Physicists

If you have a syntax error in a macro, Excel will throw up a warning. Click the
Debug button and the offending line will be highlighted. After making a correction,
click the square blue reset button—it is right under Run in the menu bar of the VBE
as shown in figure 1.7. When there is a VBA error you cannot do anything with the
worksheet until the error is removed.

1.3 Saving a macro-enabled workbook
Now we will save our work. From the Excel workspace either click the Save icon in
the Quick Access Toolbar (will Microsoft think of a new icon when we have all
forgotten about floppy discs?) or use the command File | Save. In the normal way,
give the file a name such as ‘Topic1’ but there is an extra step. Under the name box
you will see a box Excel Workbook (.xlsx) with a drop down arrow at the right.
Click the arrow and select the second option, Excel Macro-Enabled Workbook
(.xlsm), see figure 1.8. If you fail to do this Excel will detect the presence of a macro
and issue a warning. If you do not heed the warning all your modules will disappear!

Figure 1.7. The VBE interface.

Figure 1.8. The macro-enabled option in Save.

1-5


Excel® VBA for Physicists


1.4 Using constants and VB functions
Professor X wants to make a worksheet to compute the most probable, the mean,
and the root-mean-squared velocity of various gases at a specified temperature. Her
worksheet is shown in figure 1.9. Once again we will perform our calculations first
with worksheet formulas and then with UDFs. The author likes to confirm that the
two methods agree when testing a new UDF.
The formulas for the three velocities in C10:E10 are: =SQRT(2*8.3145*Temp/
(B10*10^-3)), =SQRT(8*8.3145*Temp/(PI()*B10*10^-3)), and =SQRT
((3*8.3145*Temp)/(B10*10^-3)). Note that B6 has been given the name
‘Temp’.
Open your Topic1.xlsm workbook, add a new worksheet and make it
similar to the figure. The reader may wish to open Topic1BVL.xlsm, select A1:
F29, and copy and paste to his/her Sheet2. Initially this will give #NAME! errors

Figure 1.9. Another UDF.

1-6


Excel® VBA for Physicists

in C18:E21 and C26:E29 because the Topic1.xlsm workbook lacks the referenced
UDFs.
Open the VBE. Sometimes it is expedient to have more than one module, but that
is not the case here. On Module1 add the following code below the code for the
kinetic energy function (as we are working in SI units we need the molar mass to be
in kilograms, hence the 10−3 factor):
Function Vprob(T, M)
Const R = 8.3145 ‘SI units
Vprob = Sqr(2 * R * T / (M * 10 ^ −3))

End Function
In C18 enter the formula =Vprob(Temp, B18). In figure 1.9 the inset shows
that our UDF appears in the tooltip box when we type =v.
In the function code we have declared R to be a constant and given it a value. This
prevents users from reassigning a value to R later in the code—not very likely in a
two-statement function but a potential error in longer macros. Within the code
Const R = 8.3145 ‘SI units, everything after the single quote is a
comment. Since VB functions take precedence over worksheet functions we use
its Sqr function rather than the worksheet function SQRT.
The code for Vmean is shown below; it is left as an exercise for the reader to code
Vrms:
Function Vmean(T, M)
Const R = 8.3145 ‘SI units
Pi = 4 * Atn(1)
Vmean = Sqr(8 * R * T / (Pi * M * 10 ^ −3))
End Function
We will code the UDF used in C26:E29 shortly.
Two things to note: (i) VB has no built in function for π, we could have coded Pi
= 3.14159265358979, but to guard against typing errors we choose the simple
formula; (ii) VBA permits a constant to be defined with an expression such as Const
TwoPi=2 * 3.14159265358979, but functions are not permitted in the
expression, making Const Pi = 4 * Atn(1) invalid.
While researching these formulas for these velocities, the author found several
sites that computed them. All agreed when the root-mean-squared velocity was
calculated, but there was a wide spread for the others. To test for correctness, use the
fact that vmean = ( 2π )vprop and vrms = 3 vprop . The following website gave consistent
2

results: />
1.5 User-defined array functions

It is possible to write code that returns data to more than one cell—think about the
worksheet functions LINEST and FREQUENCY. The code below computes Vprob,
Vmean, and Vrms all in one function. If you pasted C26:E29 from the author’s
1-7


Excel® VBA for Physicists

workbook, please delete those cells now. Select C26:E26, type =Velocities
(Temp,B26) and commit the formula with CTRL+SHIFT+ENTER. Cells C26:
E26 will each display {=VelocitiesV(Temp,B26)} where Excel has added the
curly braces to denote an array function. We can now drag C26:E26 down to row 29.
Function Velocities(T, M)
Dim Vel(3)
Const R = 8.3145
Pi = 4 * Atn(1)
Vel(0) = Sqr(2 * R * T / (M * 10 ^ −3))
Vel(1) = Sqr(8 * R * T / (Pi * M * 10 ^ −3))
Vel(2) = Sqr(3 * R * T / (M * 10 ^ −3))
End Function
In the first statement we use the Dim feature to define an array called ‘Vel’ having
three components. We compute values for each component and then pass the values
of the Vel array to the function named ‘Velocities’. Unless the reader is familiar with
languages like C++, the use of Vel(0) might be a bit unsettling. By default, VB
uses array indices starting with zero; chapter 2 shows how we can obtain the more
familiar first index of 1.

1.6 Notes on VBA functions
Because the marriage of Office Excel and VB was made when both were mature
applications, it is not surprising that sometimes there is a clash between them. The

reader should be aware that there are some differences between worksheet and VB
functions with the same name.
1. While the worksheet function =LOG(3) returns the logarithm of 3 to base
10, the VB expression x = Log(3) results in the logarithm to base e. To
obtain a base 10 result one codes x = Log(3)/log(10).
2. When the digit to be rounded is 5, the VB Round function rounds to make
the result even; so Round(3.5,0) and Round(4.5,0) each give 4 as the
result, and Round(−3.5,0) and Round(−4.5,0) each give −4. Contrast
this with the Excel results, which would be 4 and 5 for positive values and −4
and −5 for negative values, since Excel rounds up when x > 0 and down
when x < 0 when the digit to be rounded is 5. The VB behavior is sometimes
called ‘bankers’ rounding’, but there is little evidence that bankers use it.
3. Excel has the MOD function: =MOD(11,10) returns the value 1. VBA has the
Mod operator: the expression 11 Mod 10 also returns 1. However, the two
do not agree when one (not both) of the arguments is negative, as is shown in
table 1.1; the last two columns show alternative ways of performing the
calculations.
TRUNC and INT are similar in that both return integers. TRUNC removes
the fractional part of the number. INT rounds numbers down to the nearest
integer based on the value of the fractional part of the number. The results
from INT and TRUNC are different only when using negative numbers:
1-8


Excel® VBA for Physicists

Table 1.1. Comparing Excel’s MOD and VBA’s Mod.

a


b

MOD

Mod

a-(b*INT(a/b))

a-(b*TRUNC(a/b))

11
−11
19
−11

10
9
−13
−10

1
7
−7
−1

1
−2
6
−1


1
7
−7
−1

1
−2
6
−1

Figure 1.10. Example of output from a subroutine.

TRUNC(−4.3) returns −4, but INT(−4.3) returns −5, because −5 is the
lower number. The table above is taken from fice.com/enus/article/TRUNC-function-8B86A64C-3127-43DB-BA14-AA5CEB292721?
ui=en-US&rs=en-US&ad=US.

1.7 A simple subroutine
In this section we see a simple subroutine that asks for input from the user and,
having made a calculation, places the result on a worksheet. For the demonstration
it is convenient to stay with the molecular velocities theme.
Using the icon of an X within a circle after the last sheet tab, the reader should insert
a new worksheet. Then right click its tab and rename the sheet ‘MolVel’. Set up the
worksheet to look like figure 1.10, leaving rows 4 and 7 empty. Using the command
Insert | Illustrations | Shapes, place any shape on the worksheet and add text to it.
Navigate to the VBE and in the Project panel (top left) select Topic1. From the
menu, use Insert | Module. It is not essential to put our code in a separate module,
but it helps with the demonstration.
Enter the code shown below, this may be copied from Module2 in Topic1BVL.
xlsm:
Sub MolVel()

On Error GoTo Hades
Worksheets(“MolSpeed”).Activate
Range(“B4:D4”).ClearContents
1-9


Excel® VBA for Physicists

Range(“B7:D7”).ClearContents
Gas = InputBox(prompt:=“Give gas name or formula”)
Range(“B4”) = Gas
MolMass = InputBox(prompt:=“Give molar mass (g/mole)”)
Range(“C4”) = MolMass
mTemp = InputBox(prompt:=“Give temperature in K”)
Range(“D4”) = mTemp
Range(“B7”) = Vprob(mTemp, MolMass)
Range(“C7”) = Vmean(mTemp, MolMass)
Range(“D7”) = Vrms(mTemp, MolMass)
Hades:
End Sub
Experienced programmers may be appalled to see a ‘GoTo’, but the construct On
Error GoTo … is very common in VB programming, especially in the form On
Error GoTo … Resume Next to tell the program to ignore any error it encounters.
Here we have made up a name ‘Hades’ for a line to which the program will go when an
error is detected. The program flow is directed to the very end of the subroutine in this
circumstance. Examples of possible errors: (i) there is no worksheet called ‘MolSpeed’ or
(ii) the user fails to enter a meaningful value for one of the numeric variables MolMass
and mTemp,1 causing the various velocity functions to misfire. Note how we can access
these velocity functions even though they reside on a different module within the same
workbook. Should we wish to prevent such access we could add the word ‘Private’ at

the start of a function header—Private Function Whatever(….).
Before we proceed we need to return to the worksheet. Right click on the shape
and by selecting Assign Macro, indicate that this shape should run the subroutine
MolVel when clicked.
Next we look at various ways of calling up the subroutine.
1. Within the VBE we could use the Run command (figure 1.11) on the menu
(or its shortcut F5), or click the green arrow just below the Debug menu
command. In these cases, VBA may present a dialog box listing the macros
(i.e. subroutines) in the current VBA Project—even when there is only one!
Click on the macro of interest and then click the Run button, or just double
click the sub you wish to run. If the mouse cursor is inside a subroutine this
dialog is often skipped.
2. In the Code group (far left) of the Developer tab click on the item Macros, or
on the View tab locate the Macros group (far right), click on the Macros
tool, and select View Macros. In either case a dialog will open with a list of
macros—not just those in the current project but all those in the currently
opened workbook. The shortcut ALT+F8 results in the same dialog.
3. Click on the shape on the MolSpeed sheet. Since we have assigned it to the
MolVel subroutine this is what will run.
1
A variable must not have a name which is also a keyword, so we used mTemp rather than Temp just in case
Temp is a keyword (actually, it is not!).

1-10


Excel® VBA for Physicists

Figure 1.11. Some commands in the VBE menu.


Figure 1.12. The InputBox dialog.

When we run MolVel, Excel is told to activate the appropriate sheet, otherwise our
output could damage another worksheet. Of course, if we always ran the sub by
clicking the shape on the MolSpeed worksheet, this statement would be redundant.
Next a box pops up (figure 1.12) asking the user to name the gas. This name is then
placed in cell B4. In similar ways we obtain the molar mass and temperature in B5 and
B6, respectively. These are used by the velocity functions (Vprob, Vmean, and Vrms)
and the results of the functions are placed in cells B7:D7. Note that this subroutine that
resides in Module2 has access to functions defined in Module1. If we wished otherwise
we would add the word ‘Private’ before Function in the headers.

1.8 Linking an image to a subroutine
In figure 1.10 we have a blue rectangle which, when clicked, causes the subroutine
MolVel to run. The image can be a shape or picture. After placing it on the
worksheet right click it to bring up the dialog shown to the left in figure 1.13. The
user clicks the Assign Macro item bringing up a list of subroutines available in the
current Excel session and clicks the appropriate one.

1.9 Recording a macro
Excel has a tool for recording the user’s keystrokes and generating a subroutine that
can be used over and over. This can be useful for formatting and entering textual data.
1-11


Excel® VBA for Physicists

Figure 1.13. Linking an image to a subroutine.

Figure 1.14. The Record Macro dialog.


It cannot be used to make functions or to have a subroutine place a value in a cell.
Many users have found the Recorder useful for learning simple VBA commands, but it
must be stressed that the resulting subroutine is seldom very efficient.
Let us see an example. Open Sheet2 of the Topic1 workbook. To the left of the
status bar just after the word Ready, there is a small box which switches the recorder
on and off. The Code group of the Developer tab also has this tool. Start recording
and perform the following operations:
1. Fill in the dialog box as shown in figure 1.14 and click the OK button. We
will not bother with a shortcut.
1-12


×