excel® vba for physicists: vba for physicists a primer · excel® vba for physicists a primer ......

18

Upload: hoangliem

Post on 07-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader
Page 2: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Excel® VBA for PhysicistsA Primer

Page 3: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader
Page 4: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Excel® VBA for PhysicistsA Primer

Bernard V LiengmeSt Francis Xavier University, Nova Scotia, Canada

Morgan & Claypool Publishers

Page 5: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Copyright ª 2016 Morgan & Claypool Publishers

All rights reserved. No part of this publication may be reproduced, stored in a retrieval systemor transmitted in any form or by any means, electronic, mechanical, photocopying, recordingor otherwise, without the prior permission of the publisher, or as expressly permitted by law orunder terms agreed with the appropriate rights organization. Multiple copying is permitted inaccordance with the terms of licences issued by the Copyright Licensing Agency, the CopyrightClearance Centre and other reproduction rights organisations.

Rights & PermissionsTo obtain permission to re-use copyrighted material from Morgan & Claypool Publishers, pleasecontact [email protected].

Online supplementary data files are available at http://ej.iop.org/images/books/978-1-6817-4461-2/live/bk978-1-6817-4461-2suppdata.zip

ISBN 978-1-6817-4461-2 (ebook)ISBN 978-1-6817-4460-5 (print)ISBN 978-1-6817-4463-6 (mobi)

DOI 10.1088/978-1-6817-4461-2

Version: 20161101

IOP Concise PhysicsISSN 2053-2571 (online)ISSN 2054-7307 (print)

A Morgan & Claypool publication as part of IOP Concise PhysicsPublished by Morgan & Claypool Publishers, 40 Oak Drive, San Rafael, CA, 94903 USA

IOP Publishing, Temple Circus, Temple Way, Bristol BS1 6HG, UK

Page 6: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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

Page 7: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader
Page 8: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Contents

Preface x

Acknowledgements xi

Author biography xii

1 Introduction 1-1

1.1 Preparation 1-1

1.2 Demonstrating a simple function 1-3

1.3 Saving a macro-enabled workbook 1-5

1.4 Using constants and VB functions 1-6

1.5 User-defined array function 1-7

1.6 Notes on VBA functions 1-8

1.7 A simple subroutine 1-9

1.8 Linking an image to a subroutine 1-11

1.9 Recording a macro 1-11

1.10 Finding a home for macros 1-14

1.11 Typographical matters 1-14

2 Variables, Dim statements, and data types 2-1

2.1 Naming variables 2-1

2.2 The Dim statement 2-1

2.3 The major reason for variable declarations 2-1

2.4 Declarations in function headers and for constants 2-3

2.5 Data types 2-3

2.6 A second reason for variable declarations 2-4

2.7 Dimensioning arrays 2-4

2.8 The Set statement 2-6

2.9 The With…End With structure 2-7

3 Structured programming 3-1

3.1 Branching structures (If and Select Case) 3-1

3.2 Looping structures (For…Next and Do…While/Until) 3-4

3.3 Some further examples 3-7

vii

Page 9: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

4 The Excel object model 4-1

4.1 Examples of properties, methods and events 4-1

4.2 The Range object properties 4-3

4.3 Range object methods 4-5

4.3.1 Select, Copy, and Paste 4-5

4.3.2 Clear methods 4-7

4.3.3 Delete method 4-7

4.4 WorksheetFunction object 4-7

4.5 Workbook and worksheet events 4-12

4.5.1 Workbook event 4-12

4.5.2 Worksheet event 4-13

4.6 Code for sending email 4-14

5 Working with add-ins 5-1

5.1 Creating an add-in 5-1

5.2 Installation 5-2

5.3 Using the add-in 5-2

5.4 Making changes to the add-in 5-3

5.5 Viewing worksheets 5-3

5.6 Protecting the add-in 5-4

5.7 Reversing everything 5-4

6 Numerical integration 6-1

6.1 The trapezoid approximation 6-1

6.2 The Simpson 1/3 approximation 6-4

6.3 An aside 6-6

6.4 Monte Carlo integration 6-7

6.5 Gaussian and Romberg integration 6-8

7 Numerical methods for differential equations 7-1

7.1 Euler’s method 7-1

7.2 The Runge–Kutta fourth-order method 7-4

7.3 Simultaneous OEDs 7-6

7.4 Example of a system of two OEDs 7-6

7.5 Higher order OEDs 7-8

7.6 R–L circuit 7-8

Excel® VBA for Physicists

viii

Page 10: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

8 Finding roots 8-1

8.1 The bisection method 8-1

8.2 The successive iteration method 8-3

8.3 Root finding with Solver 8-4

8.4 Using range names 8-7

Excel® VBA for Physicists

ix

Page 11: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Preface

This work will introduce the reader to Visual Basic for Applications (VBA) anddemonstrate how it can greatly enhance Microsoft Excel® by giving users the abilityto make their own functions that can be used within a worksheet, and to createsubroutines to perform repetitive actions.

Visual Basic (VB, the parent of VBA) has its roots in the educationalprogramming language BASIC redeveloped at Dartmouth College in 1964. Inthe half-century since then, the language has evolved to become a high-poweredobject-orientated language which is no longer denigrated by aficionados oflanguage such as C++ and C#. The VBA compiler and editor is incorporatedwithin 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 andsubroutines, and to demonstrate that this is not a complex topic. The material ispresented in a manner that will allow the reader to experiment with VBAprogramming; this is the best way to learn it. The scenarios used in the examplescenter around either fairly simple physics or non-complicated mathematics, such asroot finding and numerical integration. The text, therefore, will be suitable not justfor 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 ingreater depth. For the reader who prefers a paper reference source, Excel 2007 VBAby John Green et al (2007, New York: Wiley) is an excellent book, notwithstandingits date; furthermore, it can be obtained very cheaply online.

The author is more than happy to reply to email inquiries about topics in thebook or other Excel (with or without VBA) questions. Please use the word Excel inthe subject line of each message.

Have fun learning to extend Excel with VBA!

Bernard V [email protected]

x

Page 12: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Acknowledgements

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

xi

Page 13: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

Author biography

Bernard V Liengme

Bernard V Liengme attended Imperial College London for hisundergraduate and postgraduate degrees; he held post-doctoralfellowships at Carnegie-Mellon University and the University ofBritish Columbia. He has conducted extensive research in surfacechemistry and the Mossbauer effect. He has been at St FrancisXavier University in Canada since 1968 as a Professor, Associate

Dean, and Registrar, as well as teaching chemistry and computer science. Hecurrently lectures part-time on business information systems. Bernard is also theauthor of other successful books: COBOL by Command (1996), A Guide toMicrosoft Excel for Scientists and Engineers (now in its fourth edition), A Guide toMicrosoft Excel for Business and Management (now in its second edition),ModellingPhysics with Microsoft Excel® (2014), and SMath for Physics: A Primer (2015).

xii

Page 14: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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

Page 15: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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

Page 16: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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

Page 17: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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

Page 18: Excel® VBA for Physicists: VBA for Physicists A Primer · Excel® VBA for Physicists A Primer ... 3.2 Looping structures (For…Next and Do ... This work will introduce the reader

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