Excel VBA for Physicists. A Primer

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

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

Microsoft Excel 2007 Macros and VBA

Welcome to Microsoft Excel 2013 p. 1 Customizing the QAT p. 5 Customizing the Ribbon Control p. 6 The Worksheet p. 6 Excel 2013 Specifications and

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Advanced Financial Modeling Macros. EduPristine

This chapter is intended to take you through the basic steps of using the Visual Basic

Getting started 7. Writing macros 23

Excel for Chemists. Second Edition

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

download instant at

As you probably know, Microsoft Excel is an

Saving a Workbook That Contains Macros

Macros enable you to automate almost any task that you can undertake

COMP1000 / Spreadsheets Week 2 Review

Introduction to macros

Microsoft Excel Level 2

Macros enable you to automate almost any task that you can undertake

Read Me First (Excel 2007)

Excel Advanced

Reference Services Division Presents. Excel Introductory Course

Database Concepts Using Microsoft Access

2. create the workbook file

Basic Microsoft Excel 2007

1 Welcome to Microsoft Excel 2007

Excel Template Instructions for the Glo-Brite Payroll Project (Using Excel 2010 or 2013)

Microsoft Excel 2007

Excel Intermediate

Excel Community SAMPLE CONTENT

Office 2016 Excel Basics 01 Video/Class Project #13 Excel Basics 1: Excel Grid, Formatting, Formulas, Cell References, Page Setup (O16-13)

Instructions for creating and modifying queries will be available in the future.

Mastering. Spreadsheets Q

Module 4 : Spreadsheets

Excel Macros, Links and Other Good Stuff

Global Software, Inc.'s Distribution Manager User Manual. Release V12 R5 M1

CHAPTER 1 GETTING STARTED

This document describes how to use the CAP workbook with Excel It applies to version 6b of the workbook.

Excel Programming with VBA (Macro Programming) 24 hours Getting Started

0 Mastering Microsoft Office

Applied Systems Client Network SEMINAR HANDOUT. Excel 2007: Level 2

Intermediate Microsoft Excel 2010 Tables and Printing

Experiment 1 CH Fall 2004 INTRODUCTION TO SPREADSHEETS

Microsoft Excel Office 2016/2013/2010/2007 Tips and Tricks

Excel 2010 Formulas Don't Update Automatically

Introduction to Microsoft Excel 2010

Rev Up to Excel 2010

SPREADSHEET (Excel 2007)

Excel for Auditors. by Bill Jelen and Dwayne K. Dowell. Holy Macro! Books

Introduction to Microsoft Excel

Using Microsoft Excel

You can record macros to automate tedious

PHLI Instruction (734) Introduction. Lists.

GeODin Basics Training. Introduction to GeODin

Excel Level 1

Introduction to Microsoft Excel

Office 2016 Excel Basics 06 Video/Class Project #18 Excel Basics 6: Customize Quick Access Toolbar (QAT) and Show New Ribbon Tabs

ABOUT THIS COURSE... 3 ABOUT THIS MANUAL... 4 LESSON 1: MANAGING LISTS... 5

Excel Tables and Pivot Tables

Excel4apps Web ADI Investigation with Excel4apps Wands version Excel4apps Inc.

Candy is Dandy Project (Project #12)

Microsoft Excel - Macros Explained

Customizing the Excel 2013 program window. Getting started with Excel 2013

B I Z N E T B R O A D C A S T Release Notes. BizNet Broadcast Build /5/ P a g e

Introduction to Microsoft Excel

Let s start by examining an Excel worksheet for the linear programming. Maximize P 70x 120y. subject to

Using Excel to Troubleshoot EMIS Data

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

Introduction. A cell can contain any of the following:

Lesson 4: Introduction to the Excel Spreadsheet 121

Excel VBA. Microsoft Excel is an extremely powerful tool that you can use to manipulate, analyze, and present data.

MS Excel Henrico County Public Library. I. Tour of the Excel Window

Solving Managerial Accounting Problems Using Excel for Windows

Excel 2010: Getting Started with Excel

MICROSOFT Excel 2010 Advanced Self-Study

Lesson 2. Using the Macro Recorder

x, with a range of 1-50 (You can use the randbetween command on excel)

Microsoft How to Series

Introduction to Microsoft Excel 2010

Microsoft Office Excel 2007

Excel 2010 Foundation. Excel 2010 Foundation SAMPLE

Troubleshooting and FAQs

HOW TO USE THIS BOOK... V 1 GETTING STARTED... 2

Getting Started with Excel

Fundamentals of Operating Systems. Fifth Edition

Basics: How to Calculate Standard Deviation in Excel

MS Excel Henrico County Public Library. I. Tour of the Excel Window

Visual basic tutorial problems, developed by Dr. Clement,

Excel 2013 Getting Started

Civil Engineering Computation

outlook-vba #outlookvba

Reading Lists Guide. Contents

HO-1: BASIC SPREADSHEET SKILLS - CREATING A WORKBOOK

RegressItPC installation and test instructions 1

Chapter-2 Digital Data Analysis

IV. Arranging & Viewing the Worksheet

Microsoft Excel Basics

Excel Select a template category in the Office.com Templates section. 5. Click the Download button.

European Computer Driving Licence. Advanced Spreadsheet Software BCS ITQ Level 3. Syllabus Version 2.0

Microsoft Excel is a spreadsheet tool capable of performing calculations, analyzing data and integrating information from different programs.

Teach yourself... PivotTables and PivotCharts. with. Microsoft Excel Easy to follow Step-by-step instructions Written in plain English

Transcription:

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 info@morganclaypool.com. 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 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 Acknowledgements Author biography x xi 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

Excel VBA for Physicists 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 viii

Excel VBA for Physicists 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 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 bliengme@stfx.ca 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 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

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