Download presentation
Presentation is loading. Please wait.
1
Introduction to VBA Programming
2
Many Types of Statements
VBA statements Access object model’s methods and properties Data Access Object’s methods and properties ActiveX Data Object
3
Example: To Open a Database
DAO command: Set db = OpenDatabase("c:\salesdb.mdb") Access Object Model’s Application Object methods: CurrentDB method: Set db = CurrentDB() OpenCurrentDatabase method: Set db = OpenCurrentDatabase("c:\salesb.mdb")
4
VB Modules Standard modules:
Standard modules are separated database objects containing one or many procedures. They most often contains utilities functions that are useful in many different circumstances. Create a standard module: In the database window, click Modules and New. Form/Report modules: Containing procedures belong to a form/report Create a form module: In the Form Design view, click the Code button
5
Procedures Sub procedures Functions
Private procedures: Can be called only by procedures in the same module. Public: Can be called by procedures in any module. Public is the default declaration Functions returns a value Used in an expression Public/Private
6
To Invoke a Sub Procedure
Use Call statement: Arguments must be surrounded by parentheses. Call myProcedure(arg1, arg2, …) If call is not used, arguments are not surrounded by parentheses. MyProcedure arg1, arg2, …
7
Variable Declarations
Option Explicit Dim variableName as DataType Variable naming rules: The first character must be a letter. Use only letters, digits, and underscore. Cannot contain spaces or periods. No VB keywords Naming conventions: Descriptive Consistent lower and upper case characters. Ex. Camel casing: lowerUpper, employeeName
8
VB Data Types Boolean (True/False):
Byte: Holds a whole number from 0 to 255. Date: date and time, 8 bytes. Double: real, 8 bytes Single: real, 4 bytes Integer: 2 bytes Long: 4 bytes integer Currency String Object: Holds a reference of an object Variant
9
Variable Declaration Examples
Dim empName as String Declare multiple variables with one Dim: Dim empName, dependentName, empSSN as String Dim X As Integer, Y As Single Initiatialization Dim interestRate as Double
10
Object Reference: Set Declare object variales: Dereferencing objects:
Dim varName As Database Set db = openCurrentDatabase("c:\salesb.mdb") Dereferencing objects: Set varName = Nothing
11
Variable Scope Procedural-level scope: declared in a procedure with the Dim statement Module-level: declared in a module’s declaration section (outside any procedure) with either Dim or Private keyword. Public level scope: a module variable declared with the Public statement.
12
Constants User-defined constants: Built-In constants:
Const NationalDay as date = #7/4/2005# Built-In constants: VBA, Access, DAO, ADO
13
Data Conversion Implicit conversion: When you assign a value of one data type to a variable of another data type, VB attempts to convert the value being assigned to the data type of the variable. Explicit conversion: VB.Net Functions: CStr, Ccur, CDbl, Cint, CLng, CSng, Cdate,Val, etc.
14
Date Data Type Date literals: A date literal may contain the date, the time, or both, and must be enclosed in # symbols: #1/30/2003#, #1/31/2003 2:10:00 PM# #6:30 PM#, #18:30:00#
15
Some Date Functions Now: Current date and time Time DateDiff Demo:
Days to Christmas Dim myDate1, mydate2 As Date myDate1 = Now mydate2 = #12/25/2005# MsgBox (DateDiff("d", myDate1, mydate2))
16
Testing VBA Code with Immediate Window
View/Immediate Window
17
Arithmetic and String Operators
+, -, *, /. \, ^ String Concatenation: &, + No compound operator: K=k+1, not k+=1
18
IF Statement IF condition THEN statements [ELSEIF condition-n THEN
[elseifstatements] [ELSE [elsestatements]]] End If
19
Select Case Structure SELECT CASE testexpression
[CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END SELECT
20
Select Case Example SELECT CASE temperature CASE <40
Text1.text=“cold” CASE < 60 Text1.text=“cool” CASE 60 to 80 Text1.text=“warm” CASE ELSE Text1.text=“Hot” End Select
21
Loop FOR index – start TO end [STEP step] [statements] [EXIT FOR]
NEXT index DO [{WHILE| UNTIL} condition] [EXIT DO] LOOP
22
Do While/Do Until Private Sub Command1_Click() Dim counter As Integer
Do While counter <= 5 Debug.write(counter) counter = counter + 1 Loop Text1.Text = counter End Sub Private Sub Command2_Click() Do Until counter > 5
23
With … End With Convenient shorthand to execute a series of statements on a single object. Within the block, the reference to the object is implicit and need not be written. With Text4 .BackColor = vbYellow .FontSize = 20 .Text = "testtest" End With
24
. Sub procedure: Procedures Sub SubName(Arguments) … End Sub
To call a sub procedure SUB1 CALL SUB1(Argument1, Argument2, …) Or SUB1 Argument1, Argument2, …
25
Function Private Function tax(salary) As Double tax = salary * 0.1
End Function
26
Call by Reference Call by Value
The address of the item is passed. Any changes made to the passing variable are made to the variable itself. ByVal Default Only the variable’s value is passed.
27
ByRef, ByVal example Private Sub Command2_Click() Dim myStr As String
myStr = Text0 Call ChangeTextRef(myStr) Text0 = myStr End Sub Private Sub ChangeTextRef(ByRef strInput As String) strInput = "New Text"
28
MsgBox MsgBox(prompt, other arguments)
MsgBox can return a value representing the user’s choice of buttons displayed by the box. Use Help to find constants used with the MsgBox
29
InputBox InputBox(Prompt [,Title] [, Default] [, Xpos] [, Ypos])
Xpos is the distance from the left edge of the screen, and Ypos is the distance from the top of the screen. Both are measured in twips (1/1440th of an inch). Note: The arguments are positional and optional. Enter a comma to skip an argument. cityName = InputBox("Please enter city name:“, , “SF”) If cityName = vbNullString Then MsgBox.Show ("customer click cancel") Else Text1 = cityName End If Note: vbNullString is a VB keyword representing null value.
30
Modeless form: Other forms can receive input focus while this form remains active.
Modal form: No other form can receive focus while this form remains active. DoCmd.OpenForm stDocName, , , stLinkCriteria, , acDialog Note: Macro/OpenForm/Window Mode
31
VBA Functions
32
Monthly Payment Form Text6 = -Pmt(Text2 / 12, Text4 * 12, Text0)
33
Conditional Required Field
Private Sub Form_BeforeUpdate(Cancel As Integer) If Year(Now) - Year(Birthdate) < 18 Then If IsNull(Text14) Then MsgBox ("You must enter guardian name! ") Cancel = True Text14.SetFocus End If End Sub
34
Domain Aggregate Functions
Aggregate functions provide statistical information about sets of records (a domain). For example, you can use an aggregate function to count the number of records in a particular set of records or to determine the average of values in a particular field. The two types of aggregate functions, domain aggregate functions and SQL aggregate functions, provide similar functionality but are used in different situations. The SQL aggregate functions can be included in the syntax of an SQL statement but can't be called directly from Visual Basic. Conversely, the domain aggregate functions can be called directly from Visual Basic code. They can also be included in an SQL statement, but an SQL aggregate function is generally more efficient.
36
Examples From Student form, lookup Fname:
=DLookUp("[fname]","faculty","fid='" & [Forms]![student]![fid] & "'") From Faculty form, count number of students advised by the faculty: =DCount("[FID]","Student","FID='" & [Forms]![Faculty]![Fid] & "'")
37
Function Example Function NumberOfStudents(FID)
NumberOfStudents = DCount("sid", "student", "fid='" & Forms!faculty!FID & "'") End Function
39
AccessObject Object An AccessObject object refers to a particular Microsoft Access object within the following collections. AllDataAccessPages AllDatabaseDiagrams AllForms AllFunctions AllMacros AllModules AllQueries AllReports AllStoredProcedures AllTables AllViews
40
Collection Structure Methods: Count Item(index), 0-based index Add
Remove
41
For Each … Next Dim formName As String Dim obj As AccessObject
For Each obj In Application.CurrentProject.AllForms formName = formName + obj.Name + vbCrLf Next MsgBox (formName) MsgBox ("Number of forms: " + CStr(Application.CurrentProject.AllForms.Count))
42
AccessObject Properties
CurrentView Property DateCreated Property DateModified Property FullName Property IsLoaded Property Name Property Properties Property Type Property
43
Is the Faculty form open? If so, in which view?
44
Dim intView As Integer If CurrentProject.AllForms("faculty").IsLoaded Then intView = CurrentProject.AllForms("faculty").CurrentView If intView = 0 Then MsgBox ("Design view") ElseIf intView = 1 Then MsgBox ("Form view") Else MsgBox ("Datasheet view") End If MsgBox ("Not open")
45
Error Handling
46
Overview Probably no matter how careful and meticulous you are, some time to time, there will be problems with your code or your application. Some problems will come from you. Some problems will be caused by users. And some problems will be caused by neither you nor your users. This means that there are things you can fix. Those you can avoid as much as possible. And there are situations beyond your control. Still, as much as you can, try anticipating any type of problem you imagine may occur when a user is using your application, and take action as much as possible to avoid bad situations.
47
Error Categories Syntax: A syntax error comes from your mistyping a word or forming a bad expression in your code. Run-Time: After all syntax errors have been fixed, the program may be ready for the user. Imagine that, in your code, you indicate that a picture would be loaded and displayed to the user but you forget to ship the picture or the directory of the picture indicated in your code becomes different when a user opens your application.
48
Error Categories Logic: These are errors that don't fit in any of the above categories. They could be caused by the user misusing your application, a problem with the computer on which the application is running while the same application is working fine in another computer. Because logic errors can be vague, they can also be difficult to fix.
49
Handling Errors type On Error GoTo followed by the name of the label that would deal with the error. Ex: Private Sub cmdCalculate_Click() On Error GoTo cmdCalculate_Click_Error ..... cmdCalculate_Click_Error: MsgBox "There was a problem when executing your instructions" End Sub
50
Handling Errors Ex. cmdCalculate_Click_Exit: Exit Sub cmdCalculate_ClickError: MsgBox "There was a problem when trying to perform the calculation.", _ vbOKCancel Or vbInformation, _ "Compound Interest" Resume cmdCalculate_Click_Exit End Sub
51
Array
52
Array You can declare an array to work with a set of values of the same data type. An array is a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store only one value. Refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements.
53
Declare Array For example, to store daily expenses for each day of the year, you can declare one array variable with 365 elements, rather than declaring 365 variables. Each element in an array contains one value. The following statement declares the array variable with 365 elements. By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365. Dim curExpense(0 to 364) As Currency ‘Declaring a Fixed Array Dim sngArray() As Single ‘Declaring a Dynamic Array
54
Declare Array ReDim statement is used to change the number of dimensions, to define the number of elements, and to define the upper and lower bounds for each dimension ReDim Preserve varArray(10)
55
Set value to element of array
To set the value of an individual element, you specify the element's index. The following example assigns an initial value of 20 to each element in the array. Sub FillArray() Dim curExpense(364) As Currency Dim intI As Integer For intI = 0 to 364 curExpense(intI) = 20 Next End Sub
56
Changing the Lower Bound
You can use the Option Base statement at the top of a module to change the default index of the first element from 0 to 1. In the following example, the Option Base statement changes the index for the first element, and the Dim statement declares the array variable with 365 elements Option Base 1 Dim curExpense(365) As Currency Or Dim curExpense(1 To 365) As Currency Dim strWeekday(7 To 13) As String
57
Storing Variant Values in Arrays
One way is to declare an array of Variant data type Dim varData(3) As Variant varData(0) = "Claudia Bendel" varData(1) = "4242 Maple Blvd" varData(2) = 38 varData(3) = Format(" ", "General Date") The other way is to assign the array returned by the Array function to a Variant variable Dim varData As Variant varData = Array("Ron Bendel", "4242 Maple Blvd", 38, _ Format(" ", "General Date"))
58
Multidimensional Arrays
you can declare arrays with up to 60 dimensions Dim sngMulti(1 To 5, 1 To 10) As Single Use nested For...Next statements to process multidimensional arrays Sub FillArrayMulti() Dim intI As Integer, intJ As Integer For intI = 1 To 5 For intJ = 1 To 10 sngMulti(intI, intJ) = intI * intJ Debug.Print sngMulti(intI, intJ) Next intJ Next intI End Sub
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.