McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.

Slides:



Advertisements
Similar presentations
© Paradigm Publishing, Inc Excel 2013 Level 2 Unit 2Managing and Integrating Data and the Excel Environment Chapter 7Automating Repetitive Tasks.
Advertisements

PROGRAMMING IN VISUAL BASIC PART 1
Microsoft Office XP Microsoft Excel
Essence of programming  Branching  Repetitions.
Visual Basic for Applications. What it does Extends the features and built in functions of Excel – Create and run VB procedures – Some may be easy to.
WORKING SMART Crystal M. Thomas Henrico County DSS (804) POSSESS Central Region Member October 31, 2007.
Office 2003 Post-Advanced Concepts and Techniques M i c r o s o f t Excel Project 7 Using Macros and Visual Basic for Applications (VBA) with Excel.
Using Macros and Visual Basic for Applications (VBA) with Excel
Developing an Excel Application
Tutorial 8: Developing an Excel Application
© 2002 ComputerPREP, Inc. All rights reserved. Excel 2000: Customizing Excel and Using Macros.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Objectives 1.Identify the functions of a spreadsheet 2.Identify how spreadsheets can be used. 3.Explain the difference in columns and rows. 4.Locate specific.
Microsoft Excel 2003 Illustrated Complete with Excel Programming.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Using the Visual Basic Editor Visual Basic for Applications 1.
Adding Automated Functionality to Office Applications.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
McGraw-Hill/Irwin The Interactive Computing Series © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft Excel 2002 Exploring Formulas.
Microsoft Excel 2007 © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line.
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet? Time for Demos...
© McGraw-Hill Companies, Inc., McGraw-Hill/Irwin Extended Learning Module M Programming in Excel with VBA.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
© 2008 The McGraw-Hill Companies, Inc. All rights reserved. WORD 2007 M I C R O S O F T ® THE PROFESSIONAL APPROACH S E R I E S Lesson 22 Macros.
Copyright 2007, Paradigm Publishing Inc. EXCEL 2007 Chapter 7 BACKNEXTEND 7-1 LINKS TO OBJECTIVES Record & run a macro Record & run a macro Save as a macro-
Automating Tasks with Visual Basic. Introduction  When can’t find a readymade macro action that does the job you want, you can use Visual Basic code.
Microsoft Excel Macros & Excel Solver (IENG490)
Enhancing User Interaction Through Programming
Creating Macros Using VBA. Assigning a Macro to a Button Display the Forms toolbar. Click the Button icon. Click and drag the mouse pointer to specify.
Chapter 11: Introduction to the Visual Basic Environment Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
® Microsoft Access 2010 Tutorial 11 Using and Writing Visual Basic for Applications Code.
INSERT BOOK COVER 1Copyright © 2011 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Microsoft Office Excel 2010 by Robert Grauer, Keith.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
McGraw-Hill/Irwin The Interactive Computing Series © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft Excel 2002 Lesson 1 Introduction.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 1 Copyright © 2008 Prentice-Hall. All rights reserved. What Can I Do with a Spreadsheet.
The Advantage Series ©2005 The McGraw-Hill Companies, Inc. All rights reserved Chapter 11 Developing Applications Using Excel Microsoft Office Excel 2003.
Visual Basic for Applications Macro Programming For Microsoft Office.
OCC Network Drives  H:\  P:\ 
With Microsoft Excel 2007 Comprehensive 1e© 2008 Pearson Prentice Hall1 Chapter 1: PowerPoint Presentation GO! with Microsoft Excel ® 2007 Comprehensive.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 3 The Visual Basic Editor. Important Features of the VBE Alt-F11 will open the Visual Basic Editor. The Code window is to the right, Project Explorer.
Chapter 9 Macros And Visual Basic For Applications.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
A lesson approach © 2011 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft® Excel 2013.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
A lesson approach © 2011 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft® Excel 2013.
COMPREHENSIVE Access Tutorial 11 Using and Writing Visual Basic for Applications Code.
1 CA202 Spreadsheet Application Automating Repetitive Tasks with Macros Lecture # 12 Dammam Community College.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Macros in Excel Using VBA Time Required – 5 hours.
Chapter 10 Using Macros, Controls and Visual Basic for Applications (VBA) with Excel Microsoft Excel 2013.
McGraw-Hill/Irwin The Interactive Computing Series © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft Excel 2002 Using Macros Lesson.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
The Advantage Series ©2005 The McGraw-Hill Companies, Inc. All rights reserved Chapter 12 Introducing Visual Basic for Applications Microsoft Office Excel.
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
Excel Tutorial 8 Developing an Excel Application
VBA - Excel VBA is Visual Basic for Applications
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet?
Microsoft Access Illustrated
Microsoft Office Illustrated
Microsoft Excel 2003 Illustrated Complete
Introducing VBA Macros
Objectives Learn about Function procedures (functions), Sub procedures (subroutines), and modules Review and modify an existing subroutine in an event.
Exploring Microsoft Office Access 2007
Exploring Microsoft Excel
Presentation transcript:

McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA

Mod M-2 INTRODUCTION  VBA, which stands for Visual Basic for Applications, is a programming language developed by Microsoft  Excel, along with the other members of Microsoft Office, includes the VBA language

Mod M-3 INTRODUCTION  Excel VBA is a programming application that allows Visual Basic code to customize your Excel applications  Units of VBA code are often referred to as macros

Mod M-4 INTRODUCTION  One advantage of Excel VBA is the macro recorder  The macro recorder is a software tool that will let you record a sequence of commands in Excel and save them as a macro

Mod M-5 WHY VBA?  VBA is a programming language, but it also serves as a macro language  A macro language is a programming language that includes built-in commands that mimic the functionality available from menus and dialog boxes within an application  A macro is a set of actions recorded or written by a user

Mod M-6 WHY VBA?  Create a VBA macro to format and print a month-end sales report  Execute the macro with a single command  Trigger Excel to automatically perform many time-consuming tasks

Mod M-7 WHY VBA?  If you are able to perform an operation manually, you can use the macro recorder to capture that operation  You can use VBA to create your own worksheet functions

Mod M-8 WHY VBA?  Common uses for VBA macros:  Inserting text  Automating a task  Automating repetitive tasks  Creating a custom command

Mod M-9 WHY VBA?  Common uses for VBA macros:  Creating a custom toolbar button  Creating a custom menu command  Creating a simplified front end  Developing new worksheet functions  Creating complete, macro-driven applications

Mod M-10 VBA in a Nutshell  You perform actions in VBA by writing (or recording) code in a VBA macro  You view and edit VBA macros using the Visual Basic Editor (VBE)

Mod M-11 VBA in a Nutshell  A VBA macro consists of Sub procedures  A Sub procedure is computer code that performs some action on or with objects

Mod M-12 VBA in a Nutshell  Sub procedure example: Sub Demo() Sum = MsgBox “The answer is ” & Sum End Sub

Mod M-13 VBA in a Nutshell  A VBA macro can also have Function procedures  A Function procedure is a VBA macro that returns a single value  You can call it from another VBA macro or even use it as a function in a worksheet formula

Mod M-14 VBA in a Nutshell  Function example: Function AddTwo(arg1, arg2) AddTwo = arg1 + arg2 End Function

Mod M-15 VBA in a Nutshell  VBA manipulates objects  An object in VBA is an item available for you to control in your code  Excel provides more than 100 objects that you can manipulate

Mod M-16 VBA in a Nutshell  You can assign values to variables  A variable is a place to store a piece of information  You can use variables in your VBA macro to store such things as values, text, or property settings

Mod M-17 VBA in a Nutshell VBA FUNCTIONEXAMPLE Object Arranged in a hierarchy Excel: Workbook: Worksheet Application.Workbooks(“Book1.xls”).Worksheets(“Sheet1”) Methods Method is an action such as ClearContents Worksheets(“Sheet1”).Range(“A1”).ClearContents

Mod M-18 THE VISUAL BASIC EDITOR  The Visual Basic Editor (VBE) is a separate application where you write and edit your Visual Basic macros  You can't run the VBE separately; Excel must be running in order for the VBE to operate

Mod M-19 THE VISUAL BASIC EDITOR  The quickest way to activate the VBE is to press Alt+F11 when Excel is active  To return to Excel, press Alt+F11 again  Alt+F11 acts as a toggle between the Excel application interface and the VBE  You can also activate the VBE by using the menus within Excel  Choose Tools, then Macro, and then choose Visual Basic Editor

Mod M-20 The VBE Tools  Menu Bar  Toolbar  Project Explorer Window  Code Window  The Properties Window  The Immediate Window

Mod M-21 The VBE Tools

Mod M-22 Working with the Project Explorer  When working in the VBE, each Excel workbook that's open is a project  A project is a collection of objects arranged as an outline  Expand a project by clicking the plus sign (+)  To contract a project click the minus sign (-)

Mod M-23 Adding a New VBA Module  Follow these steps to add a new VBA module to a project: 1. Create a new workbook in Excel 2. Press Alt+F11 to activate the VBE 3. Select the project's name in the Project Explorer window 4. Choose Insert and then Module or you can use the shortcut, by using the right-mouse click, choosing Insert, and then Module

Mod M-24 Removing a VBA Module  To remove a VBA module from a project, follow these steps: 1. Select the module's name in the Project Explorer window 2. Choose File, and then Remove ModuleName

Mod M-25 Creating a Module  In general, a VBA module can hold several types of code:  Sub procedures - A set of programming instructions that performs some action  Function procedures - A set of programming instructions that returns a single value  Declarations - One or more information statements that you provide to VBA

Mod M-26 VBA Module Code  Before you can do anything meaningful, you must have some VBA code in the VBA module  You can get VBA code into a VBA macro in two ways: 1. Entering the code directly by typing it 2. Using the Excel macro recorder to record your actions and convert them to VBA code

Mod M-27 Entering Code Directly  You can type code directly into the module  You can select, copy, cut, paste, and do other things to the text  When you are entering your code directly, you use the Tab key to indent some of the lines to make your code easier to read

Mod M-28 Entering Code Directly

Mod M-29 Entering Code Directly

Mod M-30 Using the Macro Recorder 1. Activate a worksheet in the workbook 2. Choose Tools, then Macro, and then Record New Macro 3. Excel displays its Record Macro dialog box 4. Click OK to accept the defaults 5. Excel automatically inserts a new VBA module into the project 6. From this point on, Excel converts your actions into VBA code - while recording, Excel displays the word Recording in the status bar

Mod M-31 Using the Macro Recorder 7. Excel displays a miniature floating toolbar that con­tains two toolbar buttons: Stop Recording and Relative Reference 8. Choose Tools, then Options 9. Click the View tab 10. Remove the check mark from the Gridlines option 11. Click OK to close the dialog box 12. Click the Stop Recording button

Mod M-32 Using the Macro Recorder Relative Reference Button Stop Recording Button

Mod M-33 Using the Macro Recorder

Mod M-34 Using the Macro Recorder  Try the macro: 1. Activate a worksheet that has gridlines displayed 2. Choose Tools, then Macro, and then choose Macros, or press Alt+F8 3. Select Macro1 4. Click the Run button 5. Excel executes the macro, and the gridlines disappear

Mod M-35 Using the Macro Recorder Execute the chosen macro Remove the chosen macro

Mod M-36 Using the Macro Recorder  Another way to execute a macro is to press its shortcut key 1. Choose Tools, then Macro, and then Macros 2. Select the Macro1 Sub procedure name from the list box 3. Click the Options button 4. Click the Shortcut Key option and enter a letter in the box labeled Ctrl + 5. Click OK to close the Macro Options dialog box

Mod M-37 Using the Macro Recorder Remove gridlines

Mod M-38 VBA BUILDING BLOCKS  There are many ways to write a macro using Excel VBA  Write or record macros using modules or procedures  Develop user-defined functions

Mod M-39 Code Modules  All macros reside in code modules like the one on the right of the VBE window  There are two types of code modules 1. Standard modules 2. Class modules

Mod M-40 Procedures  In VBA, macros are referred to as procedures  There are two types of procedures 1. Sub procedures 2. Function procedures  The macro recorder can only produce Sub procedures

Mod M-41 Sub Procedures  Sub procedures (sometimes referred to as subroutines) start with the keyword Sub followed by the name of the procedure and opening and closing parentheses  The end of a Sub procedure is marked by the keywords End Sub

Mod M-42 Sub Procedures Sub MonthNames() Range(“B1”).Select ActiveCell.FormulaR1C1 = “Jan” Range (“C1”).Select ActiveCell.FormulaR1C1 = “Feb”. End Sub

Mod M-43 Function Procedures  Excel has hundreds of built-in worksheet Function Procedures  Choose Insert, and then the Function command to see a list of those functions  If the function you need is not already in Excel, you can write your own user defined function (or UDF) using VBA

Mod M-44 Function Procedures  A function procedure example: Function CentigradeToFahrenheit(Centigrade) CentigradeToFahrenheit = Centigrade * 9 / End Function

Mod M-45 ELEMENTS OF VBA PROGRAMMING  VBA uses many elements common to all programming languages, such as:  Comments  Variables  Constants  Data types

Mod M-46 Comments  A comment is the simplest type of VBA  VBA ignores these statements  Example: Sub CommentsExample() ‘ This procedure is a demonstration x = 0 ‘ x represents zero ‘ The next line of code will display the result MsgBox x End Sub

Mod M-47 Variables and Constants  VBA's main purpose is to manipulate data  VBA stores the data in your computer's memory  Some data, such as worksheet ranges, reside in objects and other data are stored in variables or constants

Mod M-48 Variables  Variable – name of a storage location  Examples  x = 1 (assigns the value of 1 to the variable x)  UserName = “Amy Phillips” (UserName is a string variable that can hold text)  x = x + 1 (adds 1 to x and stores it in the variable x)  DateStarted = #12/20/2004# (DateStarted is a date variable)

Mod M-49 Constants  A variable's value may (and usually does) change while your procedure is executing  A constant is a named element whose value doesn't change  Example: Const NumQuarters As Integer = 4 Const Rate =.0725 Const Period = 12 Const ModName As String = “Budget Macros”

Mod M-50 Data Types  Data types are the manner in which data types are stored in memory - for example, as integers, real numbers, or strings  Examples  Boolean  Integer  Currency  Date  String

Mod M-51 Strings  Excel and VBA can work with both numbers and text  Text is often referred to as a string  There are two types of strings in VBA: 1. Fixed-length strings are declared with a specified number of characters (the maximum length is about 65,526 characters) 2. Variable-length strings theoretically can hold as many as 2 billion characters

Mod M-52 Dates  To store dates, use the Date data type  If you do, you will be able to perform calculations with the dates

Mod M-53 Assignment Statements  An assignment statement is a VBA statement that assigns the result of an expression to a variable or an object  Examples: x = 1 x = x + 1 x = (y * 2) / (z * 2) HouseCost = FileOpen = True Range(“TheYear”).Value = 2005

Mod M-54 Operators  The precedence order for operators in VBA is exactly the same as in Excel formulas  Exponentiation has the highest precedence  Multiplication and division come next  Then addition and subtraction

Mod M-55 Operators  Arithmetic operators  Add (+), subtract (-), multiply (*), divide (/), exponentiate (^), string concatenate (&)  Logical operators  Not, And, Or, XoR (exclusion), Eqv (equivalence), Imp (implication)

Mod M-56 DECISIONS, DECISIONS, DECISIONS  VBA is a structured language  It offers standard structured decision constructs such as:  If-Then and Select Case structures  For-Next, Do-Until, and Do-While loops

Mod M-57 The If-Then Structure  Executes one or more statements based on some condition  Format If condition Then statements [Else statements]  Examples If Quantity >= 75 Then Discount = 0.25 If Quantity > 10 Then Discount = 0.1 Else Discount = 0.0

Mod M-58 The Select Case Structure  Useful for decisions involving three or more options  Often used for decisions that involve evaluating a number in a range (e.g., between 1 and 100, between 101 and 200, and so on)  See example on page M.21

Mod M-59 Looping  The term looping refers to repeating a block of statements or code numerous times  There are several looping statements to choose from:  The For-Next loop  The Do-While loop  The Do-Until loop

Mod M-60 The For-Next Loop  The looping is controlled by a counter variable, which starts at one value and stops at another value  Example: Sub FillRange() Dim Count As Integer For Count = 1 To 100 ActiveCell.Offset(Count - 1, 0) = Rnd Next Count End Sub

Mod M-61 Do-While Loop  A Do-While loop continues until a specified condition is met  Example: Sub DoWhileExample() Do While ActiveCell.Value <> Empty ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offset(1, 0).Select Loop End Sub

Mod M-62 Do-Until Loop  In a Do-Until loop, the macro executes the loop until the condition is true  Example: Sub DoUntilExample() Do Until IsEmpty (ActiveCell.Value) ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offset(l, 0).Select Loop End Sub

Mod M-63 WRAP IT UP

Mod M-64 WRAP IT UP 1. Open a new workbook 2. Create a worksheet 3. Press Alt+F11 to activate the VBE 4. Click the new workbook's name in the Project Explorer window 5. Choose Insert, then Module to insert a VBA module into the project

Mod M-65 WRAP IT UP 6. Type the following code into the Code window Type this code

Mod M-66 WRAP IT UP 7. Return to the Excel spreadsheet, make cell C10 the active cell and type in the formula =InvoiceAmount(A10, B10) 8. Copy the formula to the remaining cells

Mod M-67 WRAP IT UP