PowerPoint Equations by Visual Basic for Application...

16
This content has been downloaded from IOPscience. Please scroll down to see the full text. Download details: IP Address: 144.217.70.220 This content was downloaded on 29/05/2018 at 10:27 Please note that terms and conditions apply. You may also be interested in: Modelling Physics with Microsoft Excel® : Random events B V Liengme Interactive Learning Media for Lenses and Their Applications Using Macro Visual Basic in Microsoft PowerPoint Sari Sami Novita, Siti Nurul Khotimah and Wahyu Hidayat Preparing content-rich learning environments with VPython and Excel, controlled byVisual Basic for Applications Chandra Prayaga An Excel texttrademark model of a radioactive series D G H Andrews Injection Molding Parameters Calculations by Using Visual Basic (VB) Programming B Jain A R Tony, S Karthikeyen, B Jeslin A R Alex et al. The Euler’s Graphical User Interface Spreadsheet Calculator for Solving Ordinary Differential Equations by Visual Basic for Application Programming Kim Gaik Tay, Tau Han Cheong, Ming Foong Lee et al. Simulation of 2D Waves in Circular Membrane Using Excel Spreadsheet with Visual Basic for Teaching Activity R Eso, L O Safiuddin, L Agusu et al. Investigating complexity using Excel and Visual Basic K P Zetie

Transcript of PowerPoint Equations by Visual Basic for Application...

This content has been downloaded from IOPscience. Please scroll down to see the full text.

Download details:

IP Address: 144.217.70.220

This content was downloaded on 29/05/2018 at 10:27

Please note that terms and conditions apply.

You may also be interested in:

Modelling Physics with Microsoft Excel®

: Random eventsB V Liengme

Interactive Learning Media for Lenses and Their Applications Using Macro Visual Basic in Microsoft

PowerPoint

Sari Sami Novita, Siti Nurul Khotimah and Wahyu Hidayat

Preparing content-rich learning environments with VPython and Excel, controlled byVisual Basic for

Applications

Chandra Prayaga

An Excel texttrademark model of a radioactive series

D G H Andrews

Injection Molding Parameters Calculations by Using Visual Basic (VB) Programming

B Jain A R Tony, S Karthikeyen, B Jeslin A R Alex et al.

The Euler’s Graphical User Interface Spreadsheet Calculator for Solving Ordinary Differential

Equations by Visual Basic for Application Programming

Kim Gaik Tay, Tau Han Cheong, Ming Foong Lee et al.

Simulation of 2D Waves in Circular Membrane Using Excel Spreadsheet with Visual Basic for Teaching

Activity

R Eso, L O Safiuddin, L Agusu et al.

Investigating complexity using Excel and Visual Basic

K P Zetie

IOP Concise Physics

Excel® VBA for PhysicistsA Primer

Bernard V Liengme

Chapter 1

Introduction

Visual Basic for Applications (VBA) is a programming language that has been builtintoMicrosoftOffice sinceOffice1997. It has its roots inVisualBasic (VB), sowhenyouperform 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 toallow us to code and run macros. Then we will see how to code some examples ofsimple macros (procedures), i.e. functions and subroutines. We close with a brieflook at recording a subroutine.

1.1 PreparationThere is little to do in preparation. We start by adding the Developer tab to theExcel ribbon. Right click on the Home tab and select Customize Ribbon. This opensthe dialog box as shown in figure 1.1, click the box to the left of Developer to add acheck mark (if it is not already there), and then click the OK button in the lowerright-hand corner of the dialog. As can be seen from the title in this dialog, one canalso 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 cannow check the macro security setting. Open the Developer tab and click on MacroSecurity to open the dialog shown in figure 1.3. Make sure that the setting is Disableall macros with notification (this is the default setting and should not be changedwithout good reason.) Beginning with Office 2007, Microsoft required thatworkbooks containing macros be saved with the extension XLSM; we refer tosuch workbooks as macro-enabled. This is a security feature since a rogue macro canharm a computer. When you open a macro-enabled workbook you will see awarning as shown in figure 1.4; click on Enable Content if you trust the workbooknot to have rogue macros. If you are working with Excel 2003, your workbooks willhave the extension XLS even when they contain macros. To learn more about macrosecurity, visit https://support.office.com/en-us/article/Enable-or-disable-macros-in-Office-files-12B036FD-D140-4E74-B45E-16FED1A7E5C6.

doi:10.1088/978-1-6817-4461-2ch1 1-1 ª Morgan & Claypool Publishers 2016

You may not see this warning every time; Excel seems to remember if a specificmacro-enabled file has been opened in the same user session. At other times thewarning comes with a more ominous message (figure 1.5). It seems odd that thismessage 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. Inthis chapter the reader needs to learn how to open the VB Editor (VBE), add amodule, 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’snew workbook.

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

Figure 1.2. The ribbon with the Developer tab added.

Excel® VBA for Physicists

1-2

1.2 Demonstrating a simple functionWithin theExcel environment there are three types of function: theworksheet function(examples being SUM, AVERAGE, ACOS); VB functions (Lcase, Len, Round);

Figure 1.3. Setting the macro security.

Figure 1.4. Example of a macro warning.

Figure 1.5. Another macro warning format.

Excel® VBA for Physicists

1-3

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

Later we will see that all VB functions may be used within a UDF, but there is arestriction on which worksheet function may be used. In general, if there is anequivalent VB function then the worksheet function may not be used.

Example. A physics student needs to compute the kinetic energy given the mass andvelocity of the object. Figure 1.6 shows a sample worksheet. In column C he uses aworksheet formula to compute the kinetic energy, while column D shows how aUDF may be used. The reader should set up a worksheet like this but leave D2:D5empty for now. In B7 we have the formula = FORMULATEXT(C2), which displaysthe referenced cell’s formula.

Open the Developer tab, click on Visual Basic (the left most icon) to open theVBE. Figure 1.7 shows the VBE window, but since you have just opened it theworking space (the module area, the panel at top right) will be grey. Click on theInsert 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 farleft 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 theformula 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) andmake the correction. How disappointed will you be when on returning to theworksheet 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 worksheetuntil the worksheet is recalculated. Do this by pressing F9, or selecting a cell with theUDF (D2 for example) and double clicking it.

Figure 1.6. Example of using a UDF.

Excel® VBA for Physicists

1-4

If you have a syntax error in a macro, Excel will throw up a warning. Click theDebug 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 VBEas shown in figure 1.7. When there is a VBA error you cannot do anything with theworksheet until the error is removed.

1.3 Saving a macro-enabled workbookNow we will save our work. From the Excel workspace either click the Save icon inthe Quick Access Toolbar (will Microsoft think of a new icon when we have allforgotten 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 boxyou 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 macroand issue a warning. If you do not heed the warning all your modules will disappear!

Figure 1.8. The macro-enabled option in Save.

Figure 1.7. The VBE interface.

Excel® VBA for Physicists

1-5

1.4 Using constants and VB functionsProfessor 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. Herworksheet is shown in figure 1.9. Once again we will perform our calculations firstwith worksheet formulas and then with UDFs. The author likes to confirm that thetwo 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 itsimilar 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.

Excel® VBA for Physicists

1-6

in C18:E21 and C26:E29 because the Topic1.xlsm workbook lacks the referencedUDFs.

Open the VBE. Sometimes it is expedient to have more than one module, but thatis not the case here. On Module1 add the following code below the code for thekinetic energy function (as we are working in SI units we need the molar mass to bein kilograms, hence the 10−3 factor):

Function Vprob(T, M)Const R = 8.3145 ‘SI unitsVprob = Sqr(2 * R * T / (M * 10 ^ −3))

End Function

In C18 enter the formula =Vprob(Temp, B18). In figure 1.9 the inset showsthat 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. Thisprevents users from reassigning a value to R later in the code—not very likely in atwo-statement function but a potential error in longer macros. Within the codeConst R = 8.3145 ‘SI units, everything after the single quote is acomment. Since VB functions take precedence over worksheet functions we useits 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 codeVrms:

Function Vmean(T, M)Const R = 8.3145 ‘SI unitsPi = 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 simpleformula; (ii) VBA permits a constant to be defined with an expression such as ConstTwoPi=2 * 3.14159265358979, but functions are not permitted in theexpression, making Const Pi = 4 * Atn(1) invalid.

While researching these formulas for these velocities, the author found severalsites that computed them. All agreed when the root-mean-squared velocity wascalculated, but there was a wide spread for the others. To test for correctness, use the

fact that =π

v v( )2mean prop and =v v3

2rms prop. The following website gave consistent

results: http://hyperphysics.phy-astr.gsu.edu/hbase/kinetic/kintem.html.

1.5 User-defined array functionsIt is possible to write code that returns data to more than one cell—think about theworksheet 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

Excel® VBA for Physicists

1-7

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 thecurly 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.3145Pi = 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’ havingthree components. We compute values for each component and then pass the valuesof the Vel array to the function named ‘Velocities’. Unless the reader is familiar withlanguages like C++, the use of Vel(0) might be a bit unsettling. By default, VBuses array indices starting with zero; chapter 2 shows how we can obtain the morefamiliar first index of 1.

1.6 Notes on VBA functionsBecause the marriage of Office Excel and VB was made when both were matureapplications, it is not surprising that sometimes there is a clash between them. Thereader should be aware that there are some differences between worksheet and VBfunctions with the same name.

1. While the worksheet function =LOG(3) returns the logarithm of 3 to base10, the VB expression x = Log(3) results in the logarithm to base e. Toobtain 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 makethe result even; so Round(3.5,0) and Round(4.5,0) each give 4 as theresult, and Round(−3.5,0) and Round(−4.5,0) each give −4. Contrastthis with the Excel results, which would be 4 and 5 for positive values and −4and −5 for negative values, since Excel rounds up when x > 0 and downwhen x < 0 when the digit to be rounded is 5. The VB behavior is sometimescalled ‘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 theMod operator: the expression 11 Mod 10 also returns 1. However, the twodo not agree when one (not both) of the arguments is negative, as is shown intable 1.1; the last two columns show alternative ways of performing thecalculations.

TRUNC and INT are similar in that both return integers. TRUNC removesthe fractional part of the number. INT rounds numbers down to the nearestinteger based on the value of the fractional part of the number. The resultsfrom INT and TRUNC are different only when using negative numbers:

Excel® VBA for Physicists

1-8

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

1.7 A simple subroutineIn 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 demonstrationit is convenient to stay with the molecular velocities theme.

Using the icon of anXwithin a circle after the last sheet tab, the reader should inserta new worksheet. Then right click its tab and rename the sheet ‘MolVel’. Set up theworksheet to look like figure 1.10, leaving rows 4 and 7 empty. Using the commandInsert | 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 themenu, 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 HadesWorksheets(“MolSpeed”).ActivateRange(“B4:D4”).ClearContents

Figure 1.10. Example of output from a subroutine.

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 10 1 1 1 1−11 9 7 −2 7 −219 −13 −7 6 −7 6

−11 −10 −1 −1 −1 −1

Excel® VBA for Physicists

1-9

Range(“B7:D7”).ClearContentsGas = InputBox(prompt:=“Give gas name or formula”)Range(“B4”) = GasMolMass = InputBox(prompt:=“Give molar mass (g/mole)”)Range(“C4”) = MolMassmTemp = InputBox(prompt:=“Give temperature in K”)Range(“D4”) = mTempRange(“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 OnError GoTo … is very common in VB programming, especially in the form OnError 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 programwill go when anerror is detected. The program flow is directed to the very end of the subroutine in thiscircumstance.Examples ofpossible errors: (i) there is noworksheet called ‘MolSpeed’or(ii) the user fails to enter a meaningful value for one of the numeric variables MolMassand mTemp,1 causing the various velocity functions to misfire. Note how we can accessthese velocity functions even though they reside on a different module within the sameworkbook. Shouldwewish to prevent such access we could add the word ‘Private’ atthe start of a function header—Private Function Whatever(….).

Before we proceed we need to return to the worksheet. Right click on the shapeand by selecting Assign Macro, indicate that this shape should run the subroutineMolVel 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 menucommand. 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 doubleclick the sub you wish to run. If the mouse cursor is inside a subroutine thisdialog is often skipped.

2. In the Code group (far left) of the Developer tab click on the item Macros, oron the View tab locate the Macros group (far right), click on the Macrostool, and select View Macros. In either case a dialog will open with a list ofmacros—not just those in the current project but all those in the currentlyopened 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 theMolVel subroutine this is what will run.

1A variable must not have a name which is also a keyword, so we used mTemp rather than Temp just in caseTemp is a keyword (actually, it is not!).

Excel® VBA for Physicists

1-10

Whenwe runMolVel, Excel is told to activate the appropriate sheet, otherwise ouroutput could damage another worksheet. Of course, if we always ran the sub byclicking 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 thenplaced in cell B4. In similar ways we obtain themolarmass and temperature in B5 andB6, 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 thatresides inModule2 has access to functions defined inModule1. If we wished otherwisewe would add the word ‘Private’ before Function in the headers.

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

1.9 Recording a macroExcel has a tool for recording the user’s keystrokes and generating a subroutine thatcan be used over and over. This can be useful for formatting and entering textual data.

Figure 1.12. The InputBox dialog.

Figure 1.11. Some commands in the VBE menu.

Excel® VBA for Physicists

1-11

It cannot be used to make functions or to have a subroutine place a value in a cell.Manyusers have found theRecorder useful for learning simpleVBAcommands, but itmust 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 thestatus bar just after the word Ready, there is a small box which switches the recorderon and off. The Code group of the Developer tab also has this tool. Start recordingand perform the following operations:

1. Fill in the dialog box as shown in figure 1.14 and click the OK button. Wewill not bother with a shortcut.

Figure 1.14. The Record Macro dialog.

Figure 1.13. Linking an image to a subroutine.

Excel® VBA for Physicists

1-12

2. Hold down the CTRL key and drag the tab of Sheet2 to the left betweenSheet2 and MolSpeed. Release the CTRL key. Now we have a newworksheet called Sheet2 (2) and it is the active sheet.

3. Using tools in the font group of the Home group:i. Change the size of the type in A1:E1 and A6:C6.ii. Select A8:E13 and give the range a fill colour and change its font colour.iii. Do the same with A16:E21.iv. Click on F14.

4. Switch off the recorder.

Open the VBE and in the Topic1 project you will find the recorder addedModule3 holding the sub DuplicateSheet2. This reads:

Sub DuplicateSheet2()‘‘ DuplicateSheet2 Macro‘ Make a duplicate of Sheet2 and format some ranges‘

Sheets(“Sheet2”).SelectSheets(“Sheet2”).Copy Before:=Sheets(3)Range(“A1:E1”).SelectSelection.Font.Size = 14Selection.Font.Size = 16Range(“A6:C6”).SelectSelection.Font.Size = 14Selection.Font.Size = 16Range(“A8:E13”).SelectWith Selection.Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.ThemeColor = xlThemeColorAccent3

.TintAndShade = 0.799981688894314

.PatternTintAndShade = 0End WithWith Selection.Font

.ThemeColor = xlThemeColorAccent2

.TintAndShade = 0End WithRange(“A16:E21”).SelectWith Selection.Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.ThemeColor = xlThemeColorAccent1

.TintAndShade = 0.399975585192419

.PatternTintAndShade = 0End With

Excel® VBA for Physicists

1-13

With Selection.Font.ThemeColor = xlThemeColorAccent5.TintAndShade = −0.249977111117893

End WithRange(“F14”).Select

End Sub

The reader is encouraged to spot the pieces of code that correspond to the actionsperformed while recording. Of course, some parameters (such as Font.Size,TintAndShade) will have different values depending on what the user selected.

1.10 Finding a home for macrosWe have placed our functions and subroutines in modules stored in the currentworkbook. This is generally the safest choice. Macros housed in other workbooks areaccessible when those workbooks are open; one generally avoids this complication.

If you have macros that you wish to use in many different workbooks, then thebest course is to store them in the Personal.xlsb workbook. This workbook can bemade by starting the recorder, specifying Personal as the stage place (the third box infigure 1.14), and recoding a one-line sub. Then go to the VBE, open the Personalproject, and delete the module with the dummy subroutine.

The Personal.xlsb workbook is stored in your Xlstart folder and opens every timeExcel is started, and it is normally hidden in Excel but visible in the VBE. Thefollowing links provide further information (do not be concerned if they mentionolder versions of Excel or Windows):

• http://www.rondebruin.nl/win/personal.htm• https://support.office.com/en-us/article/Copy-your-macros-to-a-Personal-Macro-Workbook-AA439B90-F836-4381-97F0-6E4C3F5EE566?ui=en-US&rs=en-US&ad=US

Another place for macros is an Add-in workbook; we explore this topic inchapter 5.

1.11 Typographical mattersThe indentation shown in our example is not mandatory but is highly recommendedas it makes reading the code a lot easier. For example, when the statementsbetween For and Next are indented it is immediately obvious what code isrepeated.

A long statement may be split into several rows using the underscore character.For example:

Range(“A2”) = Range(“F2”).Value + Range(“C2”).Value

may be coded as

Range(“A2”) = Range(“F2”).Value _+ Range(“C2”).Value

Excel® VBA for Physicists

1-14

It is important to note that the underscore is placed just after a space in the longcode. This cannot be a space within a literal. The correct way to split a literal isdemonstrated by

Range(“A10”) = “Now is the time for all good folks to ” _& “come to the aid of the party”

Excel® VBA for Physicists

1-15