AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.

Slides:



Advertisements
Similar presentations
Integrated Business Applications with Databases (D3) Jenny Pedler
Advertisements

Introduction to Visual Basic for Applications programming in Excel.
ISOM3230 Business Applications Programming
Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.
EXCEL VBA 101 Current Status Waiting Using Excel/VBA to Speed-up Daily Data Processing An Introduction to VBA Yongjun Chen Click Me to Start …
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.
Using Macros and Visual Basic for Applications (VBA) with Excel
Tutorial 8: Developing an Excel Application
Some computer fundamentals and jargon Memory: Basic element is a bit – value = 0 or 1 Collection of “n” bits is a “byte” Collection of several bytes is.
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
Customisation The GUI in most GIS applications is sufficient for most needs. However, situations arise where you want either to: –Modify the interface,
Arrays. What is an Array? An array is a way to structure multiple pieces of data of the same type and have them readily available for multiple operations.
VBA Modules, Functions, Variables, and Constants
CVEV 118/698 Visual Basic Lecture 1 Prof. Mounir Mabsout Expert 1: Elsa Sulukdjian Expert 2: Walid El Asmar.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
VB Code Statements 3 types of VB statement The Remark statement, known as comments, are used for project documentation only Begin with an apostrophe Not.
To type the VB code behind the command button (named cmdPush), Double-Click on the Push Me (caption) command button As a result the Visual Basic Code Window.
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
VB .NET Programming Fundamentals
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
IE 212: Computational Methods for Industrial Engineering
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
XP Chapter 7 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Enhancing User Interaction Through Programming Chapter.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Enhancing User Interaction Through Programming
The animation is already done for you; just copy and paste the slide into your existing presentation. Dony Pranadiyanta, ST.
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.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Chapter 11: Introduction to the Visual Basic Environment Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
Why to Create a Procedure
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
National Diploma Unit 4 Introduction to Software Development Data types, variables and constants.
Lab 01 Forms in excel Tahani ALdweesh Insert form into your project. 2. Change form’s properties. 3. Put controls on the form. 4. Change controls’
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Types and Loops.
VBA Lab 2 I ns.Samia Al-blwi. Visual Basic Grammar Object: Visual Basic is an object-oriented language. This means that all the items in Excel are thought.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
Variables,Constants and Data types Variables temporarily stores values during the execution of an application Variables have a name and data type Declare.
Chapter 9 Macros And Visual Basic For Applications.
VB for applications. Lesson Plan Fundamentals of VB VB for handling events in Access.
Chapter 11: Introduction to VBA Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Chapter-1 Introduction to Visual Basic GUI- A GUI is a graphical (rather than purely textual) user interface to a computer. The term came into existence.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Visual Basic Programming I 56:150 Information System Design.
CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures.
CHAPTER 9 PART II. MULTIDIMENSIONAL ARRAYS Used to represent tables of values arranged in rows and columns. Table element requires two indexes: row and.
# 1# 1 What is a variable that you create? What is a constant that you create? What is an intrinsic (built-in) constant? What variables are built in?
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Programming with Microsoft Visual Basic th Edition
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Understanding Visual Basic Fundamentals CHAPTER 13 Understanding Visual Basic Fundamentals.
Controlling Program Flow with Decision Structures.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
2. Understanding VB Variables
Microsoft Access Illustrated
Excel VBA Day 3 of 3 Tom Vorves.
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Chapter 6 Variables What is VBScript?
Introduction to Computer Programming IT-104
Presentation transcript:

AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax and usage u the Excel VB programming environment u the Excel object model u an application

AE6382 VBA - Excel l What advantage is there in using VBA u extend Excel – new functions u makes it possible to use the Execl GUI environment u makes it possible to respond to events (mouse, …) u makes Windows programming API accessible u Excel can be used to control Automation servers (other software components that expose an API through COM) u by understanding how to use the Excel object model with VBA it is a small step to using Excel as an Automation server (controlled by other program)

AE6382 VBA - Excel l In order to run VBA code your security settings must be properly set u Tools | Macro | Security… u At least Medium security must be set – each macro will require user verification to run l Signed code can be run in all cases

AE6382 VBA – The Basics l Data types u Integer2 byte integer u Long4 byte integer u Single4 byte floating point u Double8 byte floating point u Currency8 byte real u Stringupto 64K characters u Byte1 byte u Boolean2 byte true or false u Date8 bytes u Object4 bytes – an object reference u Variant16 bytes + 1 byte / character

AE6382 VBA – The Basics l The variant data type is special – a variant can hold any type of data l A variable declared as variant (the default) can hold anything l The actual type of the data is kept in the data l It adds flexibility but at a cost – it requires more processing at compute time to determine what it is and how to handle it

AE6382 VBA – The Basics l Variables u must start with a letter u can contain _ and numbers u cannot exceed 255 characters in length l Within a procedure declare a variable using If a variable is not declared it will be created when used, the type will be Variant Use Option Explicit in the declarations section to require declaration of variables l VBA variables have scope restrictions u variables declared in a procedure are local to that procedure  variables declared in a module can be public or private Dim variable Dim variable As type

AE6382 VBA – The Basics l String variables l The first form is variable length l The second form is limited to 50 characters u the variable will be space filled if string is < 50 characters u the string will be truncated if the contents are > 50 characters  the Trim and RTrim functions are useful for working with fixed length strings Boolean variables contain either True or False Dim variable As String Dim variable As String * 50

AE6382 VBA – The Basics l The Object type is used to store the address (a reference) of an object u this form can be used for any object u this is referred to as late-binding, the object types are checked at runtime (slower) l The declaration of a specific object is u this form will only store Excel Worksheet objects, an attempt to put anything else into it will result in an error u this is referred to as early-binding, the object types are checked at compile time (faster) Dim variable As Object Dim variable As Worksheet

AE6382 VBA – The Basics l Arrays are declared using l Arrays can be multidimensional l The lower bound starts at zero u can explicitly specify lower bound  can use Option Base command to reset to something other than 0 The last form above is a dynamic array – it must be dimensioned using ReDim before it can be used Use ReDim Preserve to retain any existing entries in array - only the upper bound of array can be changed Dim A (1 To 10) As Double Dim B (1 To 10, 1 To 10) As Double Dim C (4,4,4) As Integer Dim D () As Double Option Base 1

AE6382 VBA – The Basics l Constants are declared using l Constants have the same scope limitations as variables Const pi = Const pi As Double =

AE6382 VBA – The Basics l User defined data types  can only be defined in the declarations section of a Module  can be Public or Private in scope l Declare variable with this type l Referencing fields Public Type SystemInfo CPU As Variant Memory As Long ColorBits As Integer Cost As Currency PurchaseDate As Date End Type Dim MySystem As SystemInfo MySystem.CPU = “Pentium” If MySystem.PurchaseDate > #1/1/2006# Then … End If

AE6382 VBA – The Basics l Watch out for u it is equivalent to Dim a, b, c As Integer Dim a As Variant Dim b As Variant Dim c As Integer

AE6382 VBA – The Basics l Objects l VBA can use pre-defined objects – such as intrinsic Excel objects VBA can create user-defined objects – Class Modules l Declaring a variable to contain an object u the first form declares that the variable will contain a reference to an object of the named class u the second form declares the variable then creates an instance of the class l To instantiate a class Dim variable As class Dim variable As New class Set variable = New class

AE6382 VBA – The Basics l Objects l To declare a variable that will refer to an instance of the Excel Worksheet class l To put a reference into it l This fragment will print the name of the worksheet “Sheet1” Dim ws1 As Worksheet Set ws1 = Worksheets(“Sheet1”) Dim ws1 As Worksheet Set ws1 = Worksheets("sheet1") Debug.Print ws1.Name

AE6382 VBA – The Basics l Objects - Collections l There is a special form of objects known as Collections l They contain references to other objects and collections l It is the mechanism by which the object hierarchy is defined l By convention, collection names are usually plural u Workbooks – list of Workbook objects u Worksheets – list of Worksheet objects u Range – list of objects that represent cells, columns, rows l The following example iterates through Workbooks collection For Each ws In Worksheets Debug.Print ws.Name Next

AE6382 VBA – The Basics l Statements l VBA implements common programming statements u logical statements u looping statements u expressions

AE6382 VBA – The Basics l Logical statements l The If Then Else statement is the basic logic test If a>10 Then … End If If a>10 Then … ElseIf a<0 Then … Else … End If If a>10 Then … Else … End If

AE6382 VBA – The Basics l Logical statements l The Select statement can be used to replace a multi-way if statement Select Case expression Case expr1 … Case expr2 … Case Else … End Select

AE6382 VBA – The Basics l Loop statements l Various Do loop forms Do While expr … Loop Do Until expr … Loop Do … Loop While expr Do … Loop Until expr

AE6382 VBA – The Basics l Loop statements l A common For loop For i=1 To 10 Debug.print i Next i For i=1 To 10 Step 2 Debug.print i Next i

AE6382 VBA – The Basics l Loop statements l Another For loop l Commonly used to iterate through collections For Each element In group … Next element For Each ws In Worksheets Debug.Print ws.Name Next

AE6382 VBA – The Basics l Procedures l Procedures in VBA are either Macros or Functions u a macro does not return a value u a function will return a value u Property functions (Get and Let) are used in Class Modules to provide access to private properties Sub Name() … End Sub Function Name() As Double … End Sub

AE6382 VBA – The Basics l Dealing with runtime errors l The On Error statement will trap errors l The error name is a label in the code In the error code a Resume statement will cause the statement that caused the error to be executed again In the error code a Resume Next statement will restart execution on the statement after the one that caused the error … On Error GoTo label … On Error GoTo check … check: …

AE6382 VBA – Programming Environment l Excel (all Office components) have a VBA programming environment, VBIDE l It consists of u the Visual Basic Editor u an Object Browser u debugging support l These are accessed from the Excel menu l There is also a set of CHM files that document the components and object models of Office (for version 10) u the Excel file is named VBAXL10.CHM u XLMAIN10.CHM is the main help file for Excel and contains VBAXL10.CHM within it u each version of Office has its own set of files u

AE6382 VBA – Programming Environment l To start the Visual Basic Editor from Excel select u Tools | Macro | Visual Basic Editor

AE6382 VBA – Programming Environment l Once in the VB Editor – to start the Object Browser select u View | Object Browser

AE6382 VBA – Programming Environment l In the Object Browser to select only the Excel objects use the pull down menu at the upper left

AE6382 VBA – Programming Environment l To view information on the Worksheet object and its Name property

AE6382 VBA – Programming Environment l The usual way to create code is to double-click on one of the Worksheet or Workbook objects in the Project Explorer and enter the code.

AE6382 VBA – Programming Environment l By using the menu item Insert it is possible to add other types of procedure containers u forms (GUI) u modules for library-like procedures u class modules for defining classes

AE6382 VBA – Excel Objects l Excel exposes all of its functionality through objects l These are directly accessible to the VBA programmer l They are also visible to other applications through COM Automation u matlab u scripting languages u other Office components

AE6382 VBA – Excel Objects l The top level object is the Workbook. l A workbook corresponds to an open XLS file l Each Workbook object is kept in the Workbooks collection l To open a workbook file use u Dim wb = Workbooks.Open(“filename) To close a workbook use the Close method on the workbook object or the Workbooks entry Other methods for use with Workbooks are Save and SaveAs

AE6382 VBA – Excel Objects l The Worksheet corresponds to a Sheet l Each Worksheet object is kept in the Worksheets collection l To add a single new Worksheet u Dim ws = Worksheets.Add(count:=1) ws.Visible = False will hide the sheet ws.Delete will delete the sheet Worksheets(“Sheet1”).Delete will delete a sheet

AE6382 VBA – Excel Objects l The Range object (collection) corresponds to a set of cells l To set a value into a cell u Worksheets(“Sheet1”).Range(“A5”).Value =

AE6382 VBA – An Example l An example found on the Internet

AE6382 VBA – An Example A view from the Visual Basic Editor