Introduction to VBA Programming

Slides:



Advertisements
Similar presentations
ISOM3230 Business Applications Programming
Advertisements

Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
Chapter 3: Using Variables and Constants
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
VBA Modules, Functions, Variables, and Constants
.NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically. –Programming in.
Introduction to VBA Programming. Many Types of Statements VBA statements Access object model’s methods and properties Data Access Object’s methods and.
VB.Net Introduction - 2. Counter Example: Keep track the number of times a user clicks a button Need to declare a variable: Dim Counter As Integer Need.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Multiple Forms & Procedures. Form Methods: –Show, Hide, Activate, Close Events: –Load, Activated, Closing, Closed.
VB.Net Introduction. .NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically.
IS437: Fall 2004 Instructor: Dr. Boris Jukic Data Types, Constants, Variables, Scope, Conversion.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
VB.Net Decisions. The If … Then Statement If condition Then Statements End If If condition Then Statements Else Statements End If Condition: –Simple condition:
VB.Net Introduction. .NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically.
VB.Net Introduction. .NET Framework.NET Framework class libraries: A large set of classes that forms the basis for objects that can be used programmatically.
VB.Net Introduction. Visual Studio 2010 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# or VB –Windows.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Dani Vainstein1 VBScript Session 9. Dani Vainstein2 What we learn last session? VBScript coding conventions. Code convention usage for constants, variables,
Chapter 3: Using Variables and Constants
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.
Why to Create a Procedure
Microsoft Access Using Visual Basic Routines. Visual Basic Datatypes Boolean Byte Currency Date Double Integer Long Object Single String Variant Hyperlink.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
VB.Net Introduction. What is programming? Writing computer programs means writing instructions in a logical sequence, that will make the computer follow.
VB Procedures. Procedures. Sub procedure: Private/Public Sub SubName(Arguments) … End Sub Private: Can only be accessed by procedures in the same form.
Outline Software and Programming Program Structure Tools for Designing Software Programming Languages Introduction to Visual Basic (VBA)
Access VBA Programming for Beginners - Class 2 - by Patrick Lasu
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.
Variables,Constants and Data types Variables temporarily stores values during the execution of an application Variables have a name and data type Declare.
Introduction to VB.NET 2005 Dr. McDaniel IDS4704 Spring 2005.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Applications Development
Overview of VBA Programming & Syntax. Programming With Objects u Objects –Properties: attributes or characteristics of an object (e.g., font size, color,
‘Tirgul’ # 2 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #2.
VB for applications. Lesson Plan Fundamentals of VB VB for handling events in Access.
Types of Visual Basic Data Numeric Data Non Numeric Data.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Visual Basic Programming I 56:150 Information System Design.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
VB.Net Introduction. Visual Studio 2008 It supports VB.Net, J#, C#, and C++. Demo: –Start page: Recent projects –Starting project: File/New Project/Project.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language.
Understanding Visual Basic Fundamentals CHAPTER 13 Understanding Visual Basic Fundamentals.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
Access VBA Programming for Beginners - Class 3 -
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
Visual Basic 6 (VB6) Data Types, And Operators
Introduction to VBA Programming
Chapter 3: Using Variables and Constants
2. Understanding VB Variables
Chapter 6 Variables What is VBScript?
T. Jumana Abu Shmais – AOU - Riyadh
VBScript Session 7 Dani Vainstein.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
VB.Net Introduction.
Introduction to Computer Programming IT-104
Presentation transcript:

Introduction to VBA Programming

Many Types of Statements VBA statements Access object model’s methods and properties Data Access Object’s methods and properties ActiveX Data Object

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")

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

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

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, …

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

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

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

Object Reference: Set Declare object variales: Dereferencing objects: Dim varName As Database Set db = openCurrentDatabase("c:\salesb.mdb") Dereferencing objects: Set varName = Nothing

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.

Constants User-defined constants: Built-In constants: Const NationalDay as date = #7/4/2005# Built-In constants: VBA, Access, DAO, ADO

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.

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#

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))

Testing VBA Code with Immediate Window View/Immediate Window

Arithmetic and String Operators +, -, *, /. \, ^ String Concatenation: &, + No compound operator: K=k+1, not k+=1

IF Statement IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End If

Select Case Structure SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END SELECT

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

Loop FOR index – start TO end [STEP step] [statements] [EXIT FOR] NEXT index DO [{WHILE| UNTIL} condition] [EXIT DO] LOOP

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

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

. Sub procedure: Procedures Sub SubName(Arguments) … End Sub To call a sub procedure SUB1 CALL SUB1(Argument1, Argument2, …) Or SUB1 Argument1, Argument2, …

Function Private Function tax(salary) As Double tax = salary * 0.1 End Function

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.

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"

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

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.

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

VBA Functions

Monthly Payment Form Text6 = -Pmt(Text2 / 12, Text4 * 12, Text0)

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

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.

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] & "'")

Function Example Function NumberOfStudents(FID) NumberOfStudents = DCount("sid", "student", "fid='" & Forms!faculty!FID & "'") End Function

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

Collection Structure Methods: Count Item(index), 0-based index Add Remove

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))

AccessObject Properties CurrentView Property DateCreated Property DateModified Property FullName Property IsLoaded Property Name Property Properties Property Type Property

Is the Faculty form open? If so, in which view?

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")