Visual Basic for Applications

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

Writing Macros in Microsoft Excel 2003

Excel & Visual Basic for Applications (VBA)

Excel & Visual Basic for Applications (VBA)

RIT Installation Instructions

EXCEL VBA ( MACRO PROGRAMMING ) LEVEL SEPTEMBER AM-5.00PM MENARA PJ@AMCORP PETALING JAYA

Working with Macros and VBA in Excel 2007

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

Unleashing Hidden Powers of Inventor with the API Part 1. Getting Started with Inventor VBA Hello Inventor!

Easy Map Excel Tool USER GUIDE

Hands-on Exercise 1: VBA Coding Basics

Programming in Access VBA

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Migrating to Excel 2010 from Excel Excel - Microsoft Office 1 of 1

VBA PROGRAMMING FOR EXCEL FREDRIC B. GLUCK

LabVIEW Report Generation Toolkit for Microsoft Office User Guide

Database Automation using VBA

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

Introduction. Why (GIS) Programming? Streamline routine/repetitive procedures Implement new algorithms Customize user applications

Final Exam Review: VBA

with VBA

Microsoft VBA Programming

How to test and debug an ASP.NET application

The FTS Interactive Trader lets you create program trading strategies, as follows:

USC Marshall School of Business Marshall Information Services

Visual Basic Programming for Excel

LabVIEW Report Generation Toolkit for Microsoft Office

Module 2 - Multiplication Table - Part 1-1

Financial Data Access with SQL, Excel & VBA

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

Excel basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

Introduction to Microsoft Access 2003

Getting Started. Tutorial RIT API

Microsoft Excel 2013 Tutorial

Siemens Applied Automation Page 1 11/26/03 9:57 PM. Maxum ODBC 3.11

Microsoft Excel 2013: Using a Data Entry Form

MS Excel. Handout: Level 2. elearning Department. Copyright 2016 CMS e-learning Department. All Rights Reserved. Page 1 of 11

What is Microsoft Excel?

Automate tasks with Visual Basic macros

SPV Reporting Tool VBA Code User Guide. Last Updated: December, 2009

Construction Administrators Work Smart with Excel Programming and Functions. OTEC 2014 Session 78 Robert Henry

Q&As: Microsoft Excel 2013: Chapter 2

To add a data form to excel - you need to have the insert form table active - to make it active and add it to excel do the following:

Excel macros made easy

Integrating Microsoft Word with Other Office Applications

Report Generator Manual

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

Highline Excel 2016 Class 26: Macro Recorder

Word 2010: Mail Merge to with Attachments

Macros in Word & Excel

Overview of sharing and collaborating on Excel data

Microsoft Excel Introduction to Microsoft Excel 2007

Microsoft Excel Understanding the Basics

Creating Datalogging Applications in Microsoft Excel

The FTS Real Time System lets you create algorithmic trading strategies, as follows:

To create a histogram, you must organize the data in two columns on the worksheet. These columns must contain the following data:

Section 1: Ribbon Customization

This chapter is completely devoid of any hands-on training material. It

MS Access Lab 2. Topic: Tables

Tips and Tricks SAGE ACCPAC INTELLIGENCE

SHA 6050 Solver and VBA Lab

A Concise Guide for Beginners LIEW VOON KIONG

warpct.com Working with MS Excel 2003 Workbook courseware by WARP! Computer Training

Formulas & Functions in Microsoft Excel

Visual Basic: Objects and collections

Excel Reporting with 1010data

Visual Basic - Modules and Procedures

EXCEL FINANCIAL USES

3. (1.0 point) To ungroup worksheets, you can click a sheet of a sheet not in the group. a. index b. panel c. tab d. pane

Mail Merge Creating Mailing Labels 3/23/2011

Macros allow you to integrate existing Excel reports with a new information system

EXCEL Tutorial: How to use EXCEL for Graphs and Calculations.

Excel 2007 Basic knowledge

Microsoft Migrating to Word 2010 from Word 2003

SPSS: Getting Started. For Windows

MS WORD 2007 (PC) Macros and Track Changes Please note the latest Macintosh version of MS Word does not have Macros.

Microsoft Office Access 2007 Basics

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

VB.NET Programming Fundamentals

Visual Basic for Applications - Programming Excel. Michael Schacht Hansen

Assembling a Watershed Mailing List

Excel & Visual Basic for Applications (VBA)

Fig. 1 The finished UserForm project.

Programming Excel Macros

Part 1: An Introduction

Microsoft Excel 2013: Macro to apply Custom Margins, Titles, Gridlines, Autofit Width & Add Macro to Quick Access Toolbar & How to Delete a Macro.

PULSE Automation programming in Visual Basic. From BK training lectures arranged by Jiří Tůma & Radovan Zadražil

Add an Audit Trail to your Access Database

Access Tutorial 1 Creating a Database

To launch the Microsoft Excel program, locate the Microsoft Excel icon, and double click.

Using the Advanced Tier Data Collection Tool. A Troubleshooting Guide

A Microsoft Access Based System, Using SAS as a Background Number Cruncher David Kiasi, Applications Alternatives, Upper Marlboro, MD

Release Document Version: User Guide: SAP BusinessObjects Analysis, edition for Microsoft Office

In This Issue: Excel Sorting with Text and Numbers

Access Tutorial 13: Event-Driven Programming Using Macros

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8

CREATING FORMAL REPORT. using MICROSOFT WORD. and EXCEL

P R E M I E R. Microsoft Excel 2007 VBA (Macros) Premier Training Limited 4 Ravey Street London EC2A 4QP Telephone +44 (0)

Excel Formatting: Best Practices in Financial Models

Netezza Workbench Documentation

Transcription:

Visual Basic for Applications (VBA) Goals: ² Familiarity & experience with solving problems algorithmically. ² Familiarity with Visual Basic for Applications (VBA). VBA/Excel dialect. ² Empower you to build useful applications and to learn more on your own. ² Get you comfortable in a programming environment. Note: But you have to do a lot of work on your own! Lectures are to provide you a map. You must make the trip yourself. (cf., VBATutor.xls) File: misnotes-vba-slides-s1999.tex. 1

File: misnotes-vba-slides.tex. Created: February 13, 1998. Modi ed version of vb1-19970228.ppt. Modi ed: 19980329, 19980326, 19980214. See also: VBATutor.xls. File: misnotes-vba-slides-s1999.tex, modi ed February 8, 1999. 1-1

Goals for lecture 1. Assuming: ² Famliarity with the basic concepts of macros in Excel (which are written in VBA). ² Know how to record and run a macro, and examine and edit its code in the Visual Basic Editor. Then: 1. Use the Visual Basic Editor to create a simple VBA program (Sub) and call it for execution from a button on a worksheet. 2. Use the Visual Basic Editor to create a simple VBA program (Function) and call it for execution from a cell in a worksheet. 3. Introduce the core structure of VBA programs. 4. Introduce program variables (cf., Worksheets("Lecture1") code module Lecture1) 2

See VBATutor.xls, Worksheets("Lecture1") and code module Lecture1. 2-1

Macros ² Programs in VBA. R^ole of VB and VBA for Microsoft. ² What is VBAnExcel good for? { Assembling, \gluing together," applications in MS O±ce. (Larger issue: \component-based applications.") { Utility (small job) programming, e.g., for data preparation and manipulation, for programming the interface,... { For learning how to program. { For prototype programming. { For learning about modern software concepts (e.g., OOP) and development environments (now a good one in Excel for VBA). 3

More on macros ² Recording macros { Tools ) Macro ) RecordNew Macro... { Stop, relative addressing { Running the macro: Tools ) Macro ) Macros... { Viewing the macro: Tools ) Macro ) Visual Basic Editor Alt+F11 3-1

Recorded macro, called Bob Sub Bob() ' ' Bob Macro ' Macro recorded 2/13/98 by Steven O. Kimbrough ' ' Range("B3:C4").Select Selection.Copy Range("A1").Select ActiveSheet.Paste Application.CutCopyMode = False Range("A1").Select End Sub 4

1. This is VBA code written by the macro recorder. You can edit it just as you would code you had written. 2. Later we'll see details of VBA syntax, etc. For now note that, e.g., Range("B3:C4") is an object which has the method Select. Range("B3:C4").Select means \Select the object Range("B3:C4"). But note how readable the code is. 3. Application is also an object (here, Excel itself) but CutCopyMode is not a method. Rather, it is a property, which as it happens can be true or false. Here we are setting this property ofappication to False. 4. In general, think in terms of: Objects which have methods (which do things) and properties (which can have di erent values). Related to object-oriented programming: close but not quite. Still, a pervasive and very useful metaphor in Microsoft O±ce products. 5. Note comment signs. 4-1

Basics of Visual Basic for Applications ² VB, VBA, VBAnExcel, VBAnWord,... ² Macro modules ² Subs ² Functions ² Variables & declaring them ² Structure of a VBAnExcel application 5

A simple Sub 1. Tools ) Macro ) Visual Basic Editor 2. Insert ) Module (Not: Class Module) 3. View ) Properties Window 4. Then write some code: Sub HelloWorld() MsgBox "Hello world!" End Sub ² Use the VB Help menu item to search on MsgBox. (And use it generally and often!) ² Subs do things, but do not return values. Functions do things, and do return values. 6

Note: ² The editor is helpful. Always type lower case and make the editor do the conversion to upper case a good error-prevention strategy. ² Run the macro from the Editor (put the cursor in the code and click the Run button on the menubar) ² Run the macro from Excel (Tools ) Macro ) Macros... ) 6-1

Now, make it run from Excel...... 1. View ) Toolbars ) Control Toolbox 2. Select and draw a button. 3. Right-click with the button selected ) Properties. Set the properties as desired, then close the Property Window. 4. Right-click the button selected ) View Code 5. Add a call tohelloword: Private Sub cmdhellowold_click() HelloWorld End Sub 6. Return to Excel, exit design mode, and click the button. 7

A simple Function 1. Tools ) Macro ) Visual Basic Editor 2. Select a code module, e.g., the one with Sub HelloWord. 3. Add code and save work: Function dblutility(x, Hi, Lo, Risk) As Double dblutility = ((X - Lo) / (Hi - Lo)) ^ Risk End Function 4. Return to Excel and use this function in a cell, just as any built-in Excel function. 8

Try these procedures in a code module: Function dblcubed(x As Double) As Double dblcubed = X ^ 3 End Function Sub CubeMe() Dim dbldanumber As Double dbldanumber = _ InputBox("What number " & _ "would you like to cube?") dbldanumber = dblcubed(dbldanumber) MsgBox "And the answer is " & dbldanumber End Sub ² Dim dbldanumber As Double declares (Dimensions) the program variable dbldanumber as type Double (precision oating point). ² for line continuations. & for string concatenation. 9

VBAnExcel Programs. Are collections of Subs andfunctions (and Declarations). Typically they: 1. Are called (started) from Excel. 2. Read in information. From, e.g., worksheets, dialog boxes, les, databases. 3. Store this information in variables. 4. Computationally manipulate the variables. 5. Write out the information. To., e.g., worksheets, dialog boxes, les, databases. Basic concepts at hand, details now follow. 10

Recall: VBAnExcel Programs. Are collections of Subs andfunctions (and Declarations). Typically they: 1. Are called (started) from Excel. 2. Read in information. From, e.g., worksheets, dialog boxes, les, databases. 3. Store this information in variables. 4. Computationally manipulate the variables. 5. Write out the information. To., e.g., worksheets, dialog boxes, les, databases. 11

Variables Expressions (think of names) in programs that can hold di erent values at di erent times. ² X, Hi, Lo, Risk in thedblutility function. Option Explicit Sub FirstVariableExample() Dim I As Integer Dim MyFirstVariable As Integer 'Note: Dim I, MyFirstVariable as Integer ' leaves I an Integer and MyFirstVariable ' as a Variant. Thanks, Bill! MyFirstVariable = 3 For I = 1 To MyFirstVariable MsgBox "Showing and counting: " & I Next I End Sub 12

Variables have data types ² Types: { Integer, Long { Single, Double { Currency { Date { String { Variant ² Why? ² Look them up in the VBA online help. 13

Programs (in general, I emphasize): ² Declare variables ² Put values into variables ² Make calculations with variables ² Store results of calculations in variables Also (especially in VBA) they: ² Manipulate application objects: call methods, read and alter properties 14

Declaring variables (in VBA) ² Variables should always be declared. { Why? { Variant if not declared. { Use Option Explicit in the declarations section to force declaration of variables. ² Variables have scope. Why? ² Declaring variables { Dim in a procedure. Scope: that procedure. { Private (or Dim) in the declarations section of a module. Scope: that module. { Public in the declarations secion of a module. Scope: entire application. 15

Value(s) of MySecondVariable? Option Explicit Private MySecondVariable As Integer Sub PublicExample1() MsgBox "We're in PublicExample1 " & _ "and MySecondVariable = " & _ MySecondVariable End Sub Sub PublicExample2() MySecondVariable = 23 MsgBox "We're in PublicExample2 " & _ "and MySecondVariable = " & _ MySecondVariable End Sub 16

1. Run PublicExample1 using the Run button in the VBA editor. MySecondVariable = 0. 2. Run PublicExample2 using the Run button in the VBA editor. MySecondVariable = 23. 3. Run PublicExample1 using the Run button in the VBA editor. MySecondVariable = 23. 4. Now Reset and try again (MySecondVariable = 0). Discuss. Emphasize that while VBA has automatically initialized MySecondVariable to 0, it's a bad idea to leave this to VBA. Always initialize variables yourself! 16-1

Reading from, and writing to, a worksheet Sub CosineHardWired() Dim MyNumber As Double MyNumber = _ Worksheets("Lecture2").Cells(9, 2).Value 'Note: Cells(9,2) = row 9, column 2 of the 'worksheet. Worksheets("Lecture2").Cells(11, 2).Value = _ Cos(MyNumber) 'This also works: 'Worksheets("Lecture2").Range("B11").Value = _ 'Cos(MyNumber) 'And suppose MyTestRange is defined B2:D13. 'Then this works, too: 'With Worksheets("Lecture2").Range("MyTestRange") '.Cells(10, 1).Value = Cos(MyNumber) 'End With End Sub Try a nonnumber in B9. Debug. Reset button. Later: the debugger. 17

1. Suppose a single cell has a name, Bob. then Worksheets("Lecture2").Range("Bob").Value = Cos(MyNumber) also works. 17-1

Goals for lecture 2. 1. Say a word or two more on program variables and how to declare them. 2. Discuss and show how in VBAnExcel to read and write information from and to worksheets. 3. Brie y introduce the Object Browser. 4. Do VBA Homework #1 (handed out today) as an in-class exercise with discussion! (cf., Worksheets("Lecture2") code module Lecture2) 18

Generalizing on reading & writing ² Reading & writing the Excel worksheet are special cases of getting and setting object properties. ² So far, the Value property of a particular object, a particular cell. ² Why not, say, the color of a cell? Sub SimpleShowColor() Dim MyTempHolder As Variant MyTempHolder = _ Worksheets(2).Cells(14, 2).Interior.ColorIndex MsgBox "The interior color of B14 is " _ & MyTempHolder & "." End Sub LOTS of objects and properties in Excel. 19

Generalizing on reading & writing (con't.) Sub GetTheWorksheetName() Dim Temp As String Temp = Range("CellBob").Worksheet.Name MsgBox "The name of the worksheet in which " & _ "the range CellBob resides is " & Temp End Sub Sub RenameMeTheWorksheet() Dim Temp As String Temp = _ InputBox("New name for this worksheet?") ActiveSheet.Name = Temp End Sub 20

The object browser, F2 in the VBA Editor ² Displays, and lets you explore, all available objects, methods, and properties. Nifty! member = (method _ property) ² Right-click on a member. Your code. Excel's code. ² Example: Look in Excel, Range class, Cells member (a property). Call for help. 21

The Object Browser (con't.) A word to the wise: Be ever vigilant. No program documentation is ever complete or completely accurate and the VBA on-line Help is no exception. Some of the descriptions are just plain wrong. Some of the code samples don't work. Any many, many \gotchas" are left unexplored. Still, if you take the documentation with a small grain of salt, you'll nd an enourmous amount of important information there. And the easiest way to get to the information is via the Object Browser. from Excel 97 Annoyances, p. 205. 22

Using VBA subs and functions in other workbooks Question: Can you use VBA macros from another workbook (without copying them)? Answer: Yes. Be sure the other workbook is open (running). Preface your macro calls with the name of the other workbook followed by a bang (!). For example, if the other workbook is theotherworkbook.xls and you want to call a function there, named theotherfunction and that function takes one argument, an integer, then you might write =theotherworkbook.xls!theotherfunction(17) in one of the cells in your workbook. 23

And now... Take a look at VBA Homework #1, handed out today. 24