You are on page 1of 12

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

Visual Basic for Applications

Table of Contents
VISUAL BASIC EDITOR.....................................................................................................................................................................2 MESSAGE BOXES ...............................................................................................................................................................................3 MESSAGE BOX EXAMPLE ......................................................................................................................................................................3 THE OBJECT MODEL ........................................................................................................................................................................3 REFERRING TO OBJECTS CONTAINED IN AN A PPLICATION OBJECT MODEL ...........................................................................................4 S REFERRING TO OBJECTS IN VBA CODE .................................................................................................................................................4 Referring to an Object Properties and Methods in VBA Code.........................................................................................................4 s The Object Browser .........................................................................................................................................................................4 Getting Help in the Object Browser ..................................................................................................................................................5 PROCEDURE LEVEL VARIABLES...................................................................................................................................................5 RULES FOR NAMING VARIABLES: ...........................................................................................................................................................5 THE OPTION EXPLICIT STATEMENT .......................................................................................................................................................5 OBJECT VARIABLES .........................................................................................................................................................................6 SELECTING THE APPROPRIATE DATA TYPE AND NAME FOR AN OBJECT VARIABLE..................................................................................6 USING THE SET STATEMENT .................................................................................................................................................................6 OBJECT VARIABLE EXAMPLE ................................................................................................................................................................6 STRING VARIABLES..........................................................................................................................................................................7 USING AN ASSIGNMENT STATEMENT TO ASSIGN A VALUE TO A STRING VARIABLE .................................................................................7 USING THE INPUTBOX F UNCTION ..........................................................................................................................................................7 CONCATENATING STRINGS ...................................................................................................................................................................8 USING THE VAL F UNCTION ...................................................................................................................................................................8 STRING VARIABLE EXAMPLE ................................................................................................................................................................9 DATE VARIABLES..............................................................................................................................................................................9 USING AN ASSIGNMENT STATEMENT TO ASSIGN A VALUE TO A DATE VARIABLE ...................................................................................9 USING VBA DATE, TIME, AND NOW F UNCTIONS ..............................................................................................................................10 S USING DATES AND TIMES IN C ALCULATIONS .......................................................................................................................................10 CONVERTING STRINGS TO DATES ........................................................................................................................................................10 DATE VARIABLE EXAMPLE .................................................................................................................................................................11 INTERNET SITES..............................................................................................................................................................................11 GLOSSARY.........................................................................................................................................................................................12

Page 1

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

VISUAL BASIC EDITOR

Figure 1

__F_ Code window __E_ Code window Close button s __B_ Dot member selection operator __G_ Full Module View button __K_ Method icon __A_ Object list box

__C_ Procedure list box __H_ Procedure View button __J_ Project Explorer window __I_ Properties window __L_ Property icon __D_ Visual Basic Editor Close button s

Page 2

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

MESSAGE BOXES
The syntax for the MsgBox command allows you to include five items called arguments. These named arguments are Prompt, Buttons, Title, HelpFile, and Context. Only the Prompt argument, which specifies the message you want the dialog box to display, is required. The other four arguments are optional, which is why they are surrounded by brackets ([]).

Message Box Example


An economics professor uses a Microsoft Access database to manage the information he keeps on his Economics 100 students. Specifically, the database contains a table named Students, a form named Student Form, and a report named Student Report. The professor uses the form to enter each student ID, name, and grade in the table, s and he uses the report to print the contents of the table. The professor wants to automatically display Remember to print the grade report.In a dialog box when the entry form is closed. This procedure will be an event procedure because it will run in response to the action of closing the form. How your message box should appear Open Student Form in Design view. In the property table click on the box to the right of the Close Event Procedure. The following code will cause this message box to appear when the Student Form is closed: Private Sub Form_Close( ) display message MsgBox prompt:= Remember to print the grade report. End Sub

THE OBJECT MODEL


All object models contain two types of objects: collection and individual objects. A collection object, or a collection, is a group of one or more individual objects referred to as a single unit. Treating a group of objects as a collection allows you to conveniently refer to all of the objects at the same time.

Page 3

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

Referring to Objects Contained in an Application Object Model s


Refer to individual objects of a collection by using the object name. Most of the object models of VBA-enabled applications s contain many objects. However, you will not routinely use all objects available to you. More typically, you will use just a few objects of an application object model.

Referring to Objects in VBA Code


To refer to any element of an application object model, you must specify the object exact location within the hierarchy. s Begin at the top of the hierarchy and work downward to the desired object. Separate each name in a certain level from the next-level name by using a dot operator. It is also possible to refer to a specific object within a collection by using the object name enclosed in quotation marks. For example, Application.Forms("ProjectsForm") Every object within an object model has a set of properties (characteristics) and methods (actions) that can be referenced within VBA code as well. Referring to an Object Properties and Methods in VBA Code s Properties describe or provide characteristics of an object. Example: Application.Forms.Count specifies that the forms collection is located immediately below the application object in the object model. Count is a property of the Forms collection that stores the number of forms currently open. Methods are actions that an object can perform on its own. Example: Quit is a method of the Application object that instructs the application to close itself when used within the following VBA instruction: Application.Quit. Note that the dot operator is used to separate an object from its property or method. The Object Browser The Object Browser permits you to view all available objects in an application and to review their properties, methods, and events. You can also display an object Help s screen through the Object Browser. To open the Object Browser click its button on the Visual Basic Editor Standard toolbar. s

Page 4

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS Getting Help in the Object Browser View an object Help s screen by clicking the Help button at the top of the Object Browser window. Select Application, then Name then Click Help.

written & taught by Sandra Ohler

PROCEDURE LEVEL VARIABLES


A procedure-level variable is declared within a procedure, which means it can be used only by that procedure. Procedurelevel variables are declared at the beginning of the procedure just below the Private Sub or Public Sub lines of instruction. A Dim statement is used to reserve a procedure-level variable. Dim variablename As datatype variablename represents the name of the variable datatype represents its data type.

Rules for naming variables:


1. The name should be descriptive. 2. The name must begin with a letter. 3. The name must contain only letters, numbers, and the underscore. No punctuation characters or spaces are allowed. 4. The name cannot be more than 255 characters long 5. The name cannot be a reserved word, such as Print, because reserved words have special meaning in VBA.

The Option Explicit Statement


One common error made when coding procedures is to misspell a variable name. By selecting option explicit, Visual Basic will tell you if you use a variable that you have not declared. To turn on Option Explicit: 1. Open Visual Basic Editor 2. Select Tools, Options 3. Check the Box in front of Require Variable Declarations 4. Click OK

Page 5

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

OBJECT VARIABLES
Selecting the Appropriate Data Type and Name for an Object Variable
The data type selected for an object variable will depend on the type of object to which the object variable points. In most cases, the data type has the same name as its corresponding object. You can use the Visual Basic Object Browser to view a complete listing of objects and their data types.

Using the Set Statement


After the Dim statement creates and initializes an object variable, the Set statement assigns the address of an object to the variable. Set objectVariableName = object, objectVariableName is the name of an object variable object is the object whose address you want to store in the variable. Example: Set frmVariableName = Application.Forms("formName")

Object Variable Example


The economics professor wants you to create a procedure that will allow him to display the report in grade order. You will run the procedure from the Open event in the report. 1. Open VB Editor (Alt-F11) 2. Select Insert Module 3. Insert Procedure 4. type DisplayByGrade in Name text box 5. Click Function option button 6. Verify the Public option button is selected 7. Click OK 8. Write in pseudocode what needs done: a. Open the Student Report b. Order the Records by Grade The following code: causes these actions to be taken: Public Function Public Function DisplayByGrade( ) declare object variable Dim rptStudent as Report open report DoCmd.OpenReport _ Reportname:= studentReport view:=acViewPreview , assign address to object variable Set rptStudent = Application.Reports( studentReport ) order records by grade rptStudent.OrderByOn = True rptStudent.OrderBy = grade End Function Notes: To assign a Report object to an object variable the report must be open. To continue a line of code on the next line, enter a space then an underscore, indent the second line of code.

Page 6

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

Call procedure from the Report Open Event 1. In Project Window, select Report_StudentReport 2. Select Open event 3. type: SelectFieldOrder 4. comment out the doCmd line which opens the report in the SelectFieldOrder function 5. Open the report

STRING VARIABLES
String variables store names of people and things. When the Dim statement is used to reserve a String variable in memory, VBA initializes the variable to a zero-length string, or empty string. An empty string is two quotation marks with nothing between them.

Using an Assignment Statement to Assign a Value to a String Variable


Assignment statements are used to assign values to numeric, Date, Boolean and String variables. Quotation marks are used to enclose the string literal constant. variablename = value Example: strName = Mary

Using the InputBox Function


One way of getting information from the user at the keyboard is to use the InputBox function, which displays one of VBA s predefined dialog boxes. This dialog box contains a title bar, message, OK and Cancel buttons, and an input area where the user may enter information. The programmer specifies the title and message, and can also enter a default value in the input area

Page 7

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS written & taught by Sandra Ohler InputBox(Prompt:= prompt [,Title:=title] [, Default:=defaultValue]). prompt is the message displayed inside the dialog box, title is the text (name) displayed in the dialog box title bar s defaultValue is the value that appears in the input area when the dialog box first opens. Example: strName = InputBox(Prompt:= What is your name? Title:= , Name Information ) Notes: Italicized items to the right of the := operator are called arguments, and the bold items to the left of the := operator are the names of the arguments. The items in square brackets ([]) are optional arguments, meaning that they are not required parts of the syntax. If a Title argument is not supplied to the InputBox function, the name of the host application (for example, Microsoft Access) appears in the dialog box title bar. If no Default argument is included, the input area will be blank when s the dialog box first opens. In VBA, a function is a set of instructions that performs a task, like a procedure. A function, however, returns a value after the task is performed. For example, the InputBox function prompts the user to enter a value from the keyboard. It then returns this value to the calling program. The value returned by the InputBox is always a string literal constant, so typically it is assigned to a String variable.

Concatenating Strings
Linking strings together is called concatenating. Strings are concatenated in VBA by use of the ampersand (&).

Using the Val Function


The Val function converts a string into a number and then returns the number. Val(String:=string) Note: VBA must be able to interpret the string as a numeric value, so the string must contain only numbers and the period; it cannot include a letter or any special character (such as a dollar sign, comma, or percent sign). If the Val function encounters an invalid character (a letter, for example) in the string, it stops converting the string to a number at that point.

Page 8

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

String Variable Example


Last time we created the DisplayByGrade function to allow the economics instructor to display an Access report named StudentReport in ascending order by the Grade field. Now we will develop a procedure that allows us to display the report in either ascending or descending order by any field we choose. 1. Select Insert, Module 2. Select Insert, Procedure 3. type SelectFieldOrder in Name text box 4. Click Function option button 5. Verify Public option button is selected 6. Click OK 7. Write Pseudocode for project a. Open StudentReport b. Use InputBox function to ptompt user to enter field name, store user response in a string variable named s strField c. Use the InputBox function to prompt the user to enter the order, either asc for ascending or desc for descending. Store the user response in a string variable named strOrder s d. Display the StudentReport report with the records sorted according to the field (strField) and order (strOrder) entered by the user. Public Function SelectFieldOrder( ) declare variables Dim strField As String, strOrder As String; enter field name strField = _ InputBox(prompt: Enter the field name (StudentID, LastName, FirstName, Grade): _ , Title:= Field Default grade , = ) enter order strOrder = InputBox(prompt:= Enter sort order (either asc or desc): _ , Title:= Order Default:= , asc ) arrange records by field and order rptStudent.OrderByOn = True rptStudent.OrderBy = strField & & strOrder End Function 8. in open Report event type: SelectFieldOrder (VBA Call statement) 9. Save 10. Open report

DATE VARIABLES
Date Variables store dates or time. Date variables are automatically initialized to the number 0. Dim variablename as Date Ex: Dim dtmBirth as Date

Using an Assignment Statement to Assign a Value to a Date Variable


The number signs (#) encloses the date literal constants. A date literal constant can be a date (#January 7, 2003# or #12/31/2002#), a time (#11:05:00 AM#), or both a date and a time (#July 4, 1980 12:05:00 PM#). Date variables can store dates ranging from January 1, 100, to December 31, 9999, and times ranging from 0:00:00 (12:00:00 AM) to 23:59:59 (11:59:59 PM). Ex.: dtmBirth = #4/4/80#

Page 9

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

Using VBA Date, Time, and Now Functions s


Date function returns the system date, which is the date maintained by your computer internal clock. s Time function returns the system time, which is the time maintained by your computer internal clock. s Now function returns both the system date and time. Format function controls the appearance of dates and times. Format(Expression:=expression, Format:=format). expression specifies the number, date, time, or string whose appearance you want to format format is the name of a predefined VBA format Public Sub AssignDisplayDate( ) declare Date variables Dim dtmCurDate as Date Dim dtmCurTime as Date Dim dtmCurDateTime as Date assign values to Date variables dtmCurDate = Date dtm CurTime = Time dtmCurDateTime = Now display contents of date variables MsgBox Prompt = dtmCurDate & vbNewLine _ DtmCurTime & vbNewLine & dtmCurDateTime End Sub

Note: The vbNewLine constant causes the insertion point to move to the next line in the message box.

Using Dates and Times in Calculations


DateAdd function adds a specified time to adate or time, then returns the new date or time DateAdd(Interval:=interval, Number:=number, Date:=date) Example: DtmNew = DateAdd(Interval:= yyyy Number:=2, Date:=#1/1/2001#) , Result: Assigns 1/1/2003 to the dtmNew variable DateDiff function determines the time interval between two dates DateDiff(Interval:=interval, Date1:=date1, Date2:=date2) Example: IntDay = DateDiff(Interval:= , Date1:=#1/1/20002#, dat2:= #1/31/2002#) d Result: Assigns 30 to intDay Valid Settings for the Interval Argument Interval Setting Description yyyy Year q Quarter m Month y Day of year d Day w Weekday ww Week h Hour n Minute s Second

Converting Strings to Dates


DateValue function takes a string expression and returns the date equivalent dtmVariable = DateValue(Date:=stringExpression)

TimeValue function takes a string expression and returns the time equivalent dtmVariable = TimeValue(Time:=stringExpression

Page 10

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler

Date Variable Example


We are using Access (Carlisle.mdb) to keep track of 10 projects assigned to students in an Introduction to Programming course. The database contains a Projects table that includes fields for the project number, the date the professor assigned the project, and the project due date, which is always seven days after the assigned date. The database also includes a s form named ProjectsForm. We will create a procedure to calculate a project due date based on the assigned date he s enters in the form. Pseudocode for this project: 1. Use the InputBox function to prompt the user to enter the assigned date. Store the user response in a string s variable named strAssign. 2. Use the Date Value function to convert the string stored in the strAssign variable to a date, and then assign the result to a Date variable named dtmAssign 3. use the DateAdd function to calculate the due date, which is seven days from the assigned date. Assign the result to a Date variable named dtmDue. 4. Assign the assigned date, which is contained in the dtmAssign variable, to the txtAssignDate text box in the ProjectsForm form. 5. Assign the due date, which is contained in the dtmDue variable, to the txtDueDate text box in the ProjectsForm form. Public Function AssignDate( ) declare variables and assign address to object variable Dim strAssign as String, dtmAssign As Date, dtmDue As Date enter date assigned strAssign = InputBox( Enter date assigned: title:= , Date Assigned Default:=Date) , convert string to a date dtmAssign = DateValue(Date:=strAssign) calculate the due date dtmDue = DateAdd(interval:= , Number:=7, Date:=dtmAssign) d assign values to controls in the form frmProjects.Controls( txtAssignDate ).Value = dtmAssign frmProjects.Controls( txtDueDate ).Value = dtmDue End Function Call function AssignDate from on enter event, then open form. Note: formObject.Controls(controlName) refers to a specific control on a form

INTERNET SITES
http://www.zdnet.com/zdhelp/filters/subfilter/0,7212,6003254,00.html http://visualbasic.about.com/compute/visualbasic/ http://www.vbatutor.com/ http://www.codd.com/vbonline/

Page 11

Thursday, May 04, 2000

Offered by the Center for Teaching and Learning @ UIS

written & taught by Sandra Ohler


Method is a predefined VBA procedure that performs low-level tasks for its object. Module object is a container that stores procedures that are not associated with a specific object of the project Now Function Returns both the system date and time. Object Browser permits you to view all available objects in an application and to review their properties, methods, and events. Object Library contains all information related to an application s object model. Object Variable a memory cell or box containing the address of an object in memory. The address tells VBA where the object is located in memory Option Explicit Forces programmer to declare all variables, helps to prevent spelling mistakes in variable names. Private Scope indicates that only the object that contains it may use the procedure Procedure A set of instructions grouped together that is used to carry out the steps necessary to complete some task within or between large software application packages like those in the Microsoft Office suite. procedure-level variable is declared within a procedure, which means it can be used only by that procedure. Project Explorer Window displays a list of all open projects and their components Properties Window Every VBA object within a project has a set of characteristics, called properties, associated with it that control the object appearance and behavior. The s properties and their values are listed in the Properties window. By default, each property is assigned a value. However, the Properties window allows you to change the values to better suit the current project. Pseudocode short English statements used to help programmers plan the steps that a procedure must take in order to perform its Public Scope means that the procedure or function can be used by all objects within the project set statement Used to assign the address of an object to an object variable. string literal constants Literal means that the characters enclosed within the quotation marks should be used literally that is, exactly as shown. Constant means that the value of the string does not change while a procedure is running. Beware of confusing String variables with string literal constants. String literal constants are stored in String variables, which are memory cells. string variables Contains any character typed from the keyboard, including spaces, letters, numbers, and symbols Time Function Returns the time maintained by the computer's internal clock. Variable Programmer-created variables can store the result of a calculation or input entered by a user via the keyboard. The term variable refers to the fact that the contents of the memory cells can vary as a procedure is running. Variables created by programmers are declared with a name and a data type. Visual Basic Editor Composed of three separate windows: The Main window, the Project Explorer window and the Properties Window. Can be opened using AltF11 Thursday, May 04, 2000

GLOSSARY
Alt F11 Opens the Visual Basic Editor Arguments Specific information needed by a procedure to perform its task - also called parameters Assignment statements are used to assign values to numeric, Date, Boolean and String variables. The syntax of an assignment statement is variablename = value Class is the formal definition of an object, including the properties that control the object appearance and the methods and s events that control its behavior. Code window VBA instructions are entered as procedure code to perform some task in the Code window. The Code window title bar shows the name of the current open file and the current object. Collection A group of one or more individual objects referred to as a single unit. Treating a group of objects as a collection allows you to conveniently refer to all of the objects at the same time. Comments serve as reminders to the programmer about the purpose of the procedure and are explanatory details for anyone reading the code. To create a comment in VBA, type an apostrophe ( before the text that is to be treated ) as a comment. Constant A named item that retains a constant value throughout the execution of a program. You can use constants anywhere in your code in place of actual values. Date Function Returns the date maintained by the computer's internal clock. Date Variables Contain a date or time Dim statement Used to reserve a procedure-level variable. The syntax for the Dim statement is Dim variablename As datatype dot member selection The period between the object and its property (or method) is called the dot member selection operator. It indicates that the property is a member of the object chosen. empty string two quotation marks with nothing between them, also called a zero length or null string event procedures procedures which run in response to some action you perform on an object Format Function controls the appearance of dates and times. Function is a set of instructions that performs a task, like a procedure. A function, however, returns a value after the task is Function procedures are procedures that may return a value Input Box Function One way of getting information from the user at the keyboard. The Input Box function returns a string. Keywords Words that have special meanings to a programming language like VBA and can not be used as variable names line continuation in VBA a space followed by an underscore allows you to continue a line of code on a second line to improve readability macros procedures which can be created, saved, and run directly within the package where they will be used Main window In Visual Basic Editor, it is displayed at the top of the screen and contains the title bar, the menu bar, and the Standard toolbar. The title bar will include the currently open filename when the Visual Basic Editor window is open on the screen. Page 12

You might also like