SlideShare a Scribd company logo
Visual Basic For Applications MS Access, Beginning Course AVB201 – Beginning Access VBA P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.dhdursoassociates.com [email_address] Module 2
COURSE OUTLINE SESSION 1: Event driven Programming in Access (3 hours). SESSION 2: VBA Language Constructs and Programming Techniques (3 hours).
Session 2: VBA Language Constructs and Programming Techniques Making Decisions: If..Else.., Select Case.. Making Repetitions simple: Do..Loop, For..Next Calling Functions and Sub Procedures Getting Interactive with Message Boxes. Using VBA Editor for effective debugging. Handling errors and missing data.
2.1 Making Decisions: If..Else, Select..Case The “IF” programming construct is one of most useful programming language structures. It lets your code make “smart” (programmed) decisions based on user input and state of variables. IF statement comes in few variants: A.  If SomeVariable = 1 Then “do this”  - short version B. If SomeVariable = 1 Then  - for making 2 choices   Do this Else   Do something else End If
2.1 ..cont Demonstration:  See Print Product Dialog Form.
..cont C.   There is a third form of IF which accommodates multiple conditions (more than 2): If “SomeVariable = 1” Then do this ElseIf “SomeVariable = 2” Then do that Else do third action End If
..cont C.   There is a third form of IF which accommodates multiple conditions (more than 2): There is no limit on how many “Else If” lines you can use. Exercise:  Use “if” to choose a day of the week and print the corresponding day name. i.e. 1 = Sunday, 2 = Monday. Write a short sub function that accepts the day of the week. To save typing just do first few days.
..cont
..cont “ SomeVariable = 1” in the previous example can be replaced with any Boolean expression that evaluates to “True” or “False”. Q: Do we all know Boolean expressions? If True, then statement following executes.  If False, the construct looks for another True condition or executes statement following Else, if no True is found.
..cont Usually there is more than one form of IF that can be used for the same problem. It takes some practice to decide which one is simplest to do the job. (Design Rule: Always try to do things as simple as possible but not simpler than it is necessary!) This last form of IF can often be replaced with the Select..Case statement, which can add to readability of the program (Select ahead).
Select .. Case “ Select..Case” construct can add significantly to readability of the program. Use it whenever there is a large selection of actions available. Syntax of SELECT: Select Case “Test Expression” Case 1 action 1 Case 2 action 2 Case Else action 3 End Select
..cont NOTE: Which Case executes depends on whether “Test Expression” evaluates to 1,2, or something Else. Exercise:  Redo your previous function using a case statement. Include all the days and an error message for bad input. Use a sub this time for practice. Hint: use Debug.Print to printout the day.
..cont 'case example Sub DaynameWithCase(Day As Integer) Select Case Day Case 1 Debug.Print "You chose Sunday" Case 2 Debug.Print "You chose Monday" Case 3 Debug.Print "You chose Tuesday" Case 4 Debug.Print "You chose Wednesday" Case 5 Debug.Print "You chose thursday" Case 6 Debug.Print "You chose Friday" Case 7 Debug.Print "You chose Saturday" Case Else Debug.Print "You entered an invalid day number" End Select End Sub
2.2 Making Repetitions Simple: For..Next, Do..Loop Same piece of code often needs to execute more than once. There are two construct available to do just that: For..Next and Do..Loop.
..cont Example  which we used for demonstrating “Decisions” also demonstrates the use of For..Next statement. For x = 1 to 5 [Step 2] print report Next x This code executes the “print report” statement 5 times. X is a counter, initialized to 1, incremented by 2 each time the “Next x” executes. 5 limits how “high” the x will go before the program continues at the next line following the “Next x” line.
2.2 Making Repetitions Simple: For..Next, Do..Loop
..cont NOTES: All values in the previous example, and in For .. Next loops in general, are variable and decided upon by the programmer or the user. The Optional [Step 2] can provide increments by more than 1 (2 here) or even counting down if a negative value is being specified (-1, -2, etc..).
Do .. Loop X = 1 DO print report x = x +1 Loop While x <= 5 Is a “Do..Loop While” version of the same program. In this case it looks more cumbersome than the For..Next, yet the condition at the end allows for more flexible conditions by using any Boolean expression. For..Next has predetermined number of executions, while in Do..Loop the x often changes inside the loop and condition becomes more dynamic. Exercise  : Revise the previous code to use a do loop.
Do .. Loop
..cont Do..Loop has several variants: Do .. Loop [While | Until condition] Do [While | Until condition] .. Loop They differ in whether condition is checked at beginning or at end of the loop. Though condition is optional it is a good idea to include it, if you ever want program to get out of the loop. “ Exit Do” is another way to get out of the loop. It must be placed inside the loop. “ Until” is just a different way of phrasing the condition. In previous example we could replace “While x < 5” with “ Until x = 5”.
2.3 Calling Functions and Sub Procedures. In well structured programs in one procedure or a function you often call one or more other procedures or functions.  Procedure calls can be as simple as stating the name of the procedure or you can use a “Call Procedure_ Name” form.  Procedures called by name are called without parenthesis even when supplied with input values. Values must be separated by a comma. “Call” form requires parenthesis.
2.3 Calling Functions and Sub Procedures. Function calls need to be assigned to some variable since they always return a value. Ex: Answer = Function Name (). Use of MsgBox is an example of both. It can be called “standalone” or by returning a value. Functions are always called with parenthesis. No “Call” form is available.
2.4 Getting Interactive with Message Boxes Message boxes display messages to the user whenever used as part of any procedure or other VBA code. Syntax: MsgBox(prompt[, buttons],[, title][, helpfile, context]) [, ] are optional. Only prompt is required. In place of numbers use intrinsic constants to display  combination of buttons: vbOKOnly, vbOKCancel, vbAbortRetryIgnore, vbYesNoCancel, vbYesNo Also vbCritical (x), vbQuestion (?), vbDefaultButton1, etc.. to add icons, set default button, etc.. For complete list, consult the online help or some other reference.
..cont Ex: Confirm record delete with a dialogue MsgBox(“Are you sure you want to delete this record?” vbYesNo, “Delete Confirmation”) Hint: add your code to the on-click even “behind” the delete button.
..cont
..cont For setting buttons, default button, and the icon simultaneously, the constants must be added: vbYesNo + vbDefaultButton2 + vbQuestion displays “Yes” and “No” buttons, sets the “No” button as the default (if someone pushes “Enter” on keyboard), and displays a question mark icon.  Try it !!
..cont Message boxes can also return a value. Value depends on which button did user push. Answer can be used to determine further action in your code. Syntax: Answer = MsgBox(“Want to delete?”, vbYesNo) If Answer = vbYes Then ..do this (ex: delete a record) If Answer = vbNo Then ..do that (ex: move on) NOTE: vbYes, vbNo are also internal VBA constant that hold appropriate returned values from user action and since they have descriptive names they are easy to use in programs. There is a named constant for each type of button.
..cont Proper use of Message Boxes in any Access application often makes a difference in how users perceive the “intuitiveness” of the application.  !! Advise: Learn and practice how to use them to guide users experience. Best program is virtually useless if users can’t understand how to use it or need to “too” frequently consult the manuals, users guides, etc.. Beside offering choices, Message Boxes are also a form of documentation, reminding you of what will happen in each case, can provide better description about run time errors, point to missing values in forms, etc..
2.5 Using VBA Editor for Effective Debugging. You will on average spend 30% of your time writing a program on debugging. Debugging, simply put, is a process of making your program run “Error Free”.  Errors come in two major types: Syntax and Logical.
..cont SYNTAX ERRORS DEFINED: Syntax errors are the simpler of the two and refer to using wrong or misspelled words, variable names, undeclared variables, wrong number of parameters passed to functions and procedures, etc.. In short, they somehow violate the “grammar” of the VBA language. Syntax errors are easy to fix.
..cont LOGICAL ERRORS DEFINED: Logical errors simply return wrong results while everything has seemingly been programmed correctly. The flaw is in your logic. They can only be detected by running code with example values and checking the results. VBA Editor, as well as VBA language, have extensive set of features to help you with the debugging process.  Use of word “bug” dates back to times when some roach literally shorted the computer circuits in early type computers.
Syntax Errors VBA provides a great deal of help dealing with Syntax errors. Each time you make a mistake and try to go to the next line, the editor will either color the faulty line in red and also provide you with description of the problem. After code is written in the Editor, it needs to be compiled. This is a second tier of help where errors not caught previously are reported as each line is checked against the VBA approved syntax. Another advantage of using the Editor for writing code is Intellisense. It displays required parameter each time you use a certain function, available properties of objects when called, etc..
Syntax Errors Demonstration:  Go to standard module that we created and do some mistakes in written procedures and functions.
Logical Errors Logical errors are best dealt with by stepping through your code line by line, checking values of variables, and supplying functions and procedures with input values where the correct or expected results are known in advance. In long programs stepping line by line, especially repeatedly through the lines there were already tested, is impractical. Setting up Breakpoints let you run code up to certain point, and stop so you can check any values. Demo:  Explore the Debug menu in VBA Editor.
..cont (some useful commands) Step Into – run the next line of code. Step Over – Run the next line of code and any code in any called procedures. Step Out – Run the entire current procedure and then stop the next line in the original – calling procedure. Run to Cursor – Move cursor to some line after current line and run all the code between. Continue – Continues running the program until the next breakpoint. Break – Stop the running program. Helps with endless loops. Reset – Stops the error process and lets you restart it from any desired line of code.
2.6 Handling Errors And Missing Data No matter what you do, there will still be conditions present in the use of a program, and beyond programmers’ control that will cause programs to occasionally malfunction. VBA as language has statements that should be used as part of any function and procedure to handle such unexpected events and to let program decide how they should be handled. Such statements are called “Error Handlers”. Some Examples: Program is processing records where some may have corrupted data. OR, connection to database could not be established but following code tries to issue a query, deletion of a record failed, etc...
..cont “ On Error Resume Next” statement placed at top of any procedure will simply ignore any errors and proceed with the next line. May be useful in processing large number of records where some may be corrupted but are hard to find. “ On Error GoTo SomeLabel” provides for a more structured error handling, where you create a label, which is followed by a code  that handles possible errors. If connection to database can not be established for example, the labeled code can display a user friendly message to the user and terminate the event. There are other features available for trapping and handling errors as part of VBA, but the idea was to introduce the concept and “make aware” of the process.
..cont (example) Private Sub cmdPrintDialog_Click() ‘  on error resume next On Error GoTo Err_cmdPrintDialog_Click ‘ may trigger if report can’t be found Dim stDocName As String Dim stLinkCriteria As String stDocName = &quot;frmPrintDialog&quot; DoCmd.OpenForm stDocName, , , stLinkCriteria Exit_cmdPrintDialog_Click: Exit Sub Err_cmdPrintDialog_Click: MsgBox Err.Description Resume Exit_cmdPrintDialog_Click End Sub
..cont (example) Exercise: add error processing code to Print Button on Products Form Hint: Modify the code in the on  click event. Change the name of the form to be launched to produce an error
..cont (example)
..cont (example)
Handling Missing Data (Nulls) Many database fields may have a value “Null” until something is entered into the field. Assigning such a field to a variable will result in an error and program execution will stop. Null is NOT a 0 or a zero length string. It is simply a non-existent piece of data. You can check for Nulls with “IsNull” function.  There is a function Nz that converts any Null into a 0, which can then be used for assignment to a variable. Therefore it is a good idea to assign database fields that allow Nulls to variables used in a program in the following way: someVariable = Nz(someDBField)
2.7 Finding a Record Can use recordset clone (more about record sets in AVB202) Clone form’s recordset Use findfirst method with a search argument Set form bookmark to clone bookmark if record found
2.7 ..cont Add a text box for SKU to frmProduct Add a button Add code to button’s on-click event
2.7 ..cont
AVB201 – End of Course Thank You for Attending the Course And Wishing You a Happy VBA Programming !! NOTE:  If interested, check our schedule for our Intermediate and Advanced VBA Courses.

More Related Content

What's hot (20)

PPTX
Vba
Juhi Mahajan
 
PPT
E learning excel vba programming lesson 1
Vijay Perepa
 
PDF
Online Advance Excel & VBA Training in India
ibinstitute0
 
PPTX
VBA
Tekish
 
PPTX
Vba part 1
Morteza Noshad
 
PDF
2016 Excel/VBA Notes
Yang Ye
 
PPTX
E learning excel vba programming lesson 4
Vijay Perepa
 
PDF
Visual Basics for Application
Raghu nath
 
DOCX
Excel vba
Almeda Asuncion
 
PPTX
Unit 1 introduction to visual basic programming
Abha Damani
 
PPTX
Intro to Excel VBA Programming
iveytechnologyclub
 
PPS
Transforming Power Point Show with VBA
DCPS
 
PPTX
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
PDF
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Philip Schwarz
 
PPT
MACROS excel
Zenobia Sukhia
 
PDF
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
PDF
Cis 1403 lab5_loops
Hamad Odhabi
 
PDF
Introduction to programming by MUFIX Commnity
mazenet
 
PPTX
How to apply a formula and macro in excel......by irfan afzal
1995786
 
PPTX
Using Vba Excel
Felix Andrian Prihatono
 
E learning excel vba programming lesson 1
Vijay Perepa
 
Online Advance Excel & VBA Training in India
ibinstitute0
 
VBA
Tekish
 
Vba part 1
Morteza Noshad
 
2016 Excel/VBA Notes
Yang Ye
 
E learning excel vba programming lesson 4
Vijay Perepa
 
Visual Basics for Application
Raghu nath
 
Excel vba
Almeda Asuncion
 
Unit 1 introduction to visual basic programming
Abha Damani
 
Intro to Excel VBA Programming
iveytechnologyclub
 
Transforming Power Point Show with VBA
DCPS
 
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Philip Schwarz
 
MACROS excel
Zenobia Sukhia
 
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
Cis 1403 lab5_loops
Hamad Odhabi
 
Introduction to programming by MUFIX Commnity
mazenet
 
How to apply a formula and macro in excel......by irfan afzal
1995786
 
Using Vba Excel
Felix Andrian Prihatono
 

Viewers also liked (20)

PPTX
Development of a Wire and Cable Extrusion Line for Processing Polyolefins Con...
LDriscoll11
 
PPTX
Muse Senser
Gayatri Rallabandi
 
PPTX
Shop Floor – Explore how ERP is used to create and mainain Work Centers, Rout...
Rootstock Software
 
PPTX
ERP 101 Series: Engineering Revisions and Engineering Change Order (ECO)
Rootstock Software
 
PPTX
ERP 101: Work Orders - The Starting Points of Manufacturing
Rootstock Software
 
PPTX
ERP 101 : Shop Floor – See how scheduling the Shop Floor through ERP controls...
Rootstock Software
 
PPTX
ERP 101: MRP - Step through an overview of this vital ERP subset
Rootstock Software
 
PPTX
ERP 101 Series: Engineering Basics - The Importance of Part Master Records an...
Rootstock Software
 
PDF
ERP 101- Introduction to ERP for Manufacturing & Distribution
Rootstock Software
 
PPTX
ERP 101: Procurement - Link Your Vendors and Purchase Part via ERP
Rootstock Software
 
PPTX
ERP 101: Inventory - Maintaining Accurate and Reliable Data
Rootstock Software
 
PPTX
Sales – See how you can link your Customers and Products via ERP
Rootstock Software
 
PPT
¿Somos animales?
JAVIER ALSINA GONZALEZ
 
PPT
Filoangeletaferrer
JAVIER ALSINA GONZALEZ
 
PPT
Alles Van Tmm
lucasnet
 
PDF
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Andres Agostini, Future Knowledgist
 
PPT
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Ryan Thornburg
 
PPTX
OpenRural's Guide to Digital Public Records in N.C.
Ryan Thornburg
 
PDF
Course Catalog
Dan D'Urso
 
PDF
IntelliStick
Rhonda Williams
 
Development of a Wire and Cable Extrusion Line for Processing Polyolefins Con...
LDriscoll11
 
Muse Senser
Gayatri Rallabandi
 
Shop Floor – Explore how ERP is used to create and mainain Work Centers, Rout...
Rootstock Software
 
ERP 101 Series: Engineering Revisions and Engineering Change Order (ECO)
Rootstock Software
 
ERP 101: Work Orders - The Starting Points of Manufacturing
Rootstock Software
 
ERP 101 : Shop Floor – See how scheduling the Shop Floor through ERP controls...
Rootstock Software
 
ERP 101: MRP - Step through an overview of this vital ERP subset
Rootstock Software
 
ERP 101 Series: Engineering Basics - The Importance of Part Master Records an...
Rootstock Software
 
ERP 101- Introduction to ERP for Manufacturing & Distribution
Rootstock Software
 
ERP 101: Procurement - Link Your Vendors and Purchase Part via ERP
Rootstock Software
 
ERP 101: Inventory - Maintaining Accurate and Reliable Data
Rootstock Software
 
Sales – See how you can link your Customers and Products via ERP
Rootstock Software
 
¿Somos animales?
JAVIER ALSINA GONZALEZ
 
Filoangeletaferrer
JAVIER ALSINA GONZALEZ
 
Alles Van Tmm
lucasnet
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Andres Agostini, Future Knowledgist
 
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Ryan Thornburg
 
OpenRural's Guide to Digital Public Records in N.C.
Ryan Thornburg
 
Course Catalog
Dan D'Urso
 
IntelliStick
Rhonda Williams
 
Ad

Similar to AVB201.2 Microsoft Access VBA Module 2 (20)

DOC
Conditional statements in vb script
Nilanjan Saha
 
PPTX
Excel VBA.pptx
GiyaShefin
 
PDF
Excel-Quick-Reference-Guide.pdf
Baojing Shi
 
PPTX
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
PrantikMaity6
 
DOCX
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
PPTX
VB Script
Satish Sukumaran
 
PPTX
CONTROL STRUCTURE IN VB
classall
 
DOCX
Vb script tutorial
Abhishek Kesharwani
 
PDF
Conditional Statements & Loops
simmis5
 
PPT
Visual basic 6.0
Aarti P
 
PPTX
Presentation on visual basic 6 (vb6)
pbarasia
 
PDF
Vb script tutorial
Abhishek Kesharwani
 
PPT
Vba class 4
Mangesh Gadre
 
PDF
Getting started with Microsoft Excel Macros
Nick Weisenberger
 
PPTX
Vbscript
Abhishek Kesharwani
 
PPTX
Vba Excel Level 2
Ben Miu CIM® FCSI A+
 
PPTX
Qtp vb scripting
Bharath Sannadi
 
PPTX
01 Database Management (re-uploaded)
bluejayjunior
 
Conditional statements in vb script
Nilanjan Saha
 
Excel VBA.pptx
GiyaShefin
 
Excel-Quick-Reference-Guide.pdf
Baojing Shi
 
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
PrantikMaity6
 
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
VB Script
Satish Sukumaran
 
CONTROL STRUCTURE IN VB
classall
 
Vb script tutorial
Abhishek Kesharwani
 
Conditional Statements & Loops
simmis5
 
Visual basic 6.0
Aarti P
 
Presentation on visual basic 6 (vb6)
pbarasia
 
Vb script tutorial
Abhishek Kesharwani
 
Vba class 4
Mangesh Gadre
 
Getting started with Microsoft Excel Macros
Nick Weisenberger
 
Vba Excel Level 2
Ben Miu CIM® FCSI A+
 
Qtp vb scripting
Bharath Sannadi
 
01 Database Management (re-uploaded)
bluejayjunior
 
Ad

More from Dan D'Urso (20)

PPT
SQL201S Accelerated Introduction to MySQL Queries
Dan D'Urso
 
PPT
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
PPTX
Database Normalization
Dan D'Urso
 
PPT
VIS201d Visio Database Diagramming
Dan D'Urso
 
PPT
PRJ101a Project 2013 Accelerated
Dan D'Urso
 
PPT
PRJ101xl Project Libre Basic Training
Dan D'Urso
 
PPT
Introduction to coding using Python
Dan D'Urso
 
PPTX
Stem conference
Dan D'Urso
 
PDF
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
PPTX
Microsoft access self joins
Dan D'Urso
 
PDF
SQL302 Intermediate SQL
Dan D'Urso
 
PDF
AIN106 Access Reporting and Analysis
Dan D'Urso
 
PPT
SQL302 Intermediate SQL Workshop 3
Dan D'Urso
 
PPT
SQL302 Intermediate SQL Workshop 2
Dan D'Urso
 
PPT
SQL302 Intermediate SQL Workshop 1
Dan D'Urso
 
PDF
SQL212 Oracle SQL Manual
Dan D'Urso
 
PDF
SQL201W MySQL SQL Manual
Dan D'Urso
 
PDF
AIN100
Dan D'Urso
 
PPT
SQL206 SQL Median
Dan D'Urso
 
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
SQL201S Accelerated Introduction to MySQL Queries
Dan D'Urso
 
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
Database Normalization
Dan D'Urso
 
VIS201d Visio Database Diagramming
Dan D'Urso
 
PRJ101a Project 2013 Accelerated
Dan D'Urso
 
PRJ101xl Project Libre Basic Training
Dan D'Urso
 
Introduction to coding using Python
Dan D'Urso
 
Stem conference
Dan D'Urso
 
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
Microsoft access self joins
Dan D'Urso
 
SQL302 Intermediate SQL
Dan D'Urso
 
AIN106 Access Reporting and Analysis
Dan D'Urso
 
SQL302 Intermediate SQL Workshop 3
Dan D'Urso
 
SQL302 Intermediate SQL Workshop 2
Dan D'Urso
 
SQL302 Intermediate SQL Workshop 1
Dan D'Urso
 
SQL212 Oracle SQL Manual
Dan D'Urso
 
SQL201W MySQL SQL Manual
Dan D'Urso
 
AIN100
Dan D'Urso
 
SQL206 SQL Median
Dan D'Urso
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 

Recently uploaded (20)

PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 

AVB201.2 Microsoft Access VBA Module 2

  • 1. Visual Basic For Applications MS Access, Beginning Course AVB201 – Beginning Access VBA P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.dhdursoassociates.com [email_address] Module 2
  • 2. COURSE OUTLINE SESSION 1: Event driven Programming in Access (3 hours). SESSION 2: VBA Language Constructs and Programming Techniques (3 hours).
  • 3. Session 2: VBA Language Constructs and Programming Techniques Making Decisions: If..Else.., Select Case.. Making Repetitions simple: Do..Loop, For..Next Calling Functions and Sub Procedures Getting Interactive with Message Boxes. Using VBA Editor for effective debugging. Handling errors and missing data.
  • 4. 2.1 Making Decisions: If..Else, Select..Case The “IF” programming construct is one of most useful programming language structures. It lets your code make “smart” (programmed) decisions based on user input and state of variables. IF statement comes in few variants: A. If SomeVariable = 1 Then “do this” - short version B. If SomeVariable = 1 Then - for making 2 choices Do this Else Do something else End If
  • 5. 2.1 ..cont Demonstration: See Print Product Dialog Form.
  • 6. ..cont C. There is a third form of IF which accommodates multiple conditions (more than 2): If “SomeVariable = 1” Then do this ElseIf “SomeVariable = 2” Then do that Else do third action End If
  • 7. ..cont C. There is a third form of IF which accommodates multiple conditions (more than 2): There is no limit on how many “Else If” lines you can use. Exercise: Use “if” to choose a day of the week and print the corresponding day name. i.e. 1 = Sunday, 2 = Monday. Write a short sub function that accepts the day of the week. To save typing just do first few days.
  • 9. ..cont “ SomeVariable = 1” in the previous example can be replaced with any Boolean expression that evaluates to “True” or “False”. Q: Do we all know Boolean expressions? If True, then statement following executes. If False, the construct looks for another True condition or executes statement following Else, if no True is found.
  • 10. ..cont Usually there is more than one form of IF that can be used for the same problem. It takes some practice to decide which one is simplest to do the job. (Design Rule: Always try to do things as simple as possible but not simpler than it is necessary!) This last form of IF can often be replaced with the Select..Case statement, which can add to readability of the program (Select ahead).
  • 11. Select .. Case “ Select..Case” construct can add significantly to readability of the program. Use it whenever there is a large selection of actions available. Syntax of SELECT: Select Case “Test Expression” Case 1 action 1 Case 2 action 2 Case Else action 3 End Select
  • 12. ..cont NOTE: Which Case executes depends on whether “Test Expression” evaluates to 1,2, or something Else. Exercise: Redo your previous function using a case statement. Include all the days and an error message for bad input. Use a sub this time for practice. Hint: use Debug.Print to printout the day.
  • 13. ..cont 'case example Sub DaynameWithCase(Day As Integer) Select Case Day Case 1 Debug.Print &quot;You chose Sunday&quot; Case 2 Debug.Print &quot;You chose Monday&quot; Case 3 Debug.Print &quot;You chose Tuesday&quot; Case 4 Debug.Print &quot;You chose Wednesday&quot; Case 5 Debug.Print &quot;You chose thursday&quot; Case 6 Debug.Print &quot;You chose Friday&quot; Case 7 Debug.Print &quot;You chose Saturday&quot; Case Else Debug.Print &quot;You entered an invalid day number&quot; End Select End Sub
  • 14. 2.2 Making Repetitions Simple: For..Next, Do..Loop Same piece of code often needs to execute more than once. There are two construct available to do just that: For..Next and Do..Loop.
  • 15. ..cont Example which we used for demonstrating “Decisions” also demonstrates the use of For..Next statement. For x = 1 to 5 [Step 2] print report Next x This code executes the “print report” statement 5 times. X is a counter, initialized to 1, incremented by 2 each time the “Next x” executes. 5 limits how “high” the x will go before the program continues at the next line following the “Next x” line.
  • 16. 2.2 Making Repetitions Simple: For..Next, Do..Loop
  • 17. ..cont NOTES: All values in the previous example, and in For .. Next loops in general, are variable and decided upon by the programmer or the user. The Optional [Step 2] can provide increments by more than 1 (2 here) or even counting down if a negative value is being specified (-1, -2, etc..).
  • 18. Do .. Loop X = 1 DO print report x = x +1 Loop While x <= 5 Is a “Do..Loop While” version of the same program. In this case it looks more cumbersome than the For..Next, yet the condition at the end allows for more flexible conditions by using any Boolean expression. For..Next has predetermined number of executions, while in Do..Loop the x often changes inside the loop and condition becomes more dynamic. Exercise : Revise the previous code to use a do loop.
  • 20. ..cont Do..Loop has several variants: Do .. Loop [While | Until condition] Do [While | Until condition] .. Loop They differ in whether condition is checked at beginning or at end of the loop. Though condition is optional it is a good idea to include it, if you ever want program to get out of the loop. “ Exit Do” is another way to get out of the loop. It must be placed inside the loop. “ Until” is just a different way of phrasing the condition. In previous example we could replace “While x < 5” with “ Until x = 5”.
  • 21. 2.3 Calling Functions and Sub Procedures. In well structured programs in one procedure or a function you often call one or more other procedures or functions. Procedure calls can be as simple as stating the name of the procedure or you can use a “Call Procedure_ Name” form. Procedures called by name are called without parenthesis even when supplied with input values. Values must be separated by a comma. “Call” form requires parenthesis.
  • 22. 2.3 Calling Functions and Sub Procedures. Function calls need to be assigned to some variable since they always return a value. Ex: Answer = Function Name (). Use of MsgBox is an example of both. It can be called “standalone” or by returning a value. Functions are always called with parenthesis. No “Call” form is available.
  • 23. 2.4 Getting Interactive with Message Boxes Message boxes display messages to the user whenever used as part of any procedure or other VBA code. Syntax: MsgBox(prompt[, buttons],[, title][, helpfile, context]) [, ] are optional. Only prompt is required. In place of numbers use intrinsic constants to display combination of buttons: vbOKOnly, vbOKCancel, vbAbortRetryIgnore, vbYesNoCancel, vbYesNo Also vbCritical (x), vbQuestion (?), vbDefaultButton1, etc.. to add icons, set default button, etc.. For complete list, consult the online help or some other reference.
  • 24. ..cont Ex: Confirm record delete with a dialogue MsgBox(“Are you sure you want to delete this record?” vbYesNo, “Delete Confirmation”) Hint: add your code to the on-click even “behind” the delete button.
  • 26. ..cont For setting buttons, default button, and the icon simultaneously, the constants must be added: vbYesNo + vbDefaultButton2 + vbQuestion displays “Yes” and “No” buttons, sets the “No” button as the default (if someone pushes “Enter” on keyboard), and displays a question mark icon. Try it !!
  • 27. ..cont Message boxes can also return a value. Value depends on which button did user push. Answer can be used to determine further action in your code. Syntax: Answer = MsgBox(“Want to delete?”, vbYesNo) If Answer = vbYes Then ..do this (ex: delete a record) If Answer = vbNo Then ..do that (ex: move on) NOTE: vbYes, vbNo are also internal VBA constant that hold appropriate returned values from user action and since they have descriptive names they are easy to use in programs. There is a named constant for each type of button.
  • 28. ..cont Proper use of Message Boxes in any Access application often makes a difference in how users perceive the “intuitiveness” of the application. !! Advise: Learn and practice how to use them to guide users experience. Best program is virtually useless if users can’t understand how to use it or need to “too” frequently consult the manuals, users guides, etc.. Beside offering choices, Message Boxes are also a form of documentation, reminding you of what will happen in each case, can provide better description about run time errors, point to missing values in forms, etc..
  • 29. 2.5 Using VBA Editor for Effective Debugging. You will on average spend 30% of your time writing a program on debugging. Debugging, simply put, is a process of making your program run “Error Free”. Errors come in two major types: Syntax and Logical.
  • 30. ..cont SYNTAX ERRORS DEFINED: Syntax errors are the simpler of the two and refer to using wrong or misspelled words, variable names, undeclared variables, wrong number of parameters passed to functions and procedures, etc.. In short, they somehow violate the “grammar” of the VBA language. Syntax errors are easy to fix.
  • 31. ..cont LOGICAL ERRORS DEFINED: Logical errors simply return wrong results while everything has seemingly been programmed correctly. The flaw is in your logic. They can only be detected by running code with example values and checking the results. VBA Editor, as well as VBA language, have extensive set of features to help you with the debugging process. Use of word “bug” dates back to times when some roach literally shorted the computer circuits in early type computers.
  • 32. Syntax Errors VBA provides a great deal of help dealing with Syntax errors. Each time you make a mistake and try to go to the next line, the editor will either color the faulty line in red and also provide you with description of the problem. After code is written in the Editor, it needs to be compiled. This is a second tier of help where errors not caught previously are reported as each line is checked against the VBA approved syntax. Another advantage of using the Editor for writing code is Intellisense. It displays required parameter each time you use a certain function, available properties of objects when called, etc..
  • 33. Syntax Errors Demonstration: Go to standard module that we created and do some mistakes in written procedures and functions.
  • 34. Logical Errors Logical errors are best dealt with by stepping through your code line by line, checking values of variables, and supplying functions and procedures with input values where the correct or expected results are known in advance. In long programs stepping line by line, especially repeatedly through the lines there were already tested, is impractical. Setting up Breakpoints let you run code up to certain point, and stop so you can check any values. Demo: Explore the Debug menu in VBA Editor.
  • 35. ..cont (some useful commands) Step Into – run the next line of code. Step Over – Run the next line of code and any code in any called procedures. Step Out – Run the entire current procedure and then stop the next line in the original – calling procedure. Run to Cursor – Move cursor to some line after current line and run all the code between. Continue – Continues running the program until the next breakpoint. Break – Stop the running program. Helps with endless loops. Reset – Stops the error process and lets you restart it from any desired line of code.
  • 36. 2.6 Handling Errors And Missing Data No matter what you do, there will still be conditions present in the use of a program, and beyond programmers’ control that will cause programs to occasionally malfunction. VBA as language has statements that should be used as part of any function and procedure to handle such unexpected events and to let program decide how they should be handled. Such statements are called “Error Handlers”. Some Examples: Program is processing records where some may have corrupted data. OR, connection to database could not be established but following code tries to issue a query, deletion of a record failed, etc...
  • 37. ..cont “ On Error Resume Next” statement placed at top of any procedure will simply ignore any errors and proceed with the next line. May be useful in processing large number of records where some may be corrupted but are hard to find. “ On Error GoTo SomeLabel” provides for a more structured error handling, where you create a label, which is followed by a code that handles possible errors. If connection to database can not be established for example, the labeled code can display a user friendly message to the user and terminate the event. There are other features available for trapping and handling errors as part of VBA, but the idea was to introduce the concept and “make aware” of the process.
  • 38. ..cont (example) Private Sub cmdPrintDialog_Click() ‘ on error resume next On Error GoTo Err_cmdPrintDialog_Click ‘ may trigger if report can’t be found Dim stDocName As String Dim stLinkCriteria As String stDocName = &quot;frmPrintDialog&quot; DoCmd.OpenForm stDocName, , , stLinkCriteria Exit_cmdPrintDialog_Click: Exit Sub Err_cmdPrintDialog_Click: MsgBox Err.Description Resume Exit_cmdPrintDialog_Click End Sub
  • 39. ..cont (example) Exercise: add error processing code to Print Button on Products Form Hint: Modify the code in the on click event. Change the name of the form to be launched to produce an error
  • 42. Handling Missing Data (Nulls) Many database fields may have a value “Null” until something is entered into the field. Assigning such a field to a variable will result in an error and program execution will stop. Null is NOT a 0 or a zero length string. It is simply a non-existent piece of data. You can check for Nulls with “IsNull” function. There is a function Nz that converts any Null into a 0, which can then be used for assignment to a variable. Therefore it is a good idea to assign database fields that allow Nulls to variables used in a program in the following way: someVariable = Nz(someDBField)
  • 43. 2.7 Finding a Record Can use recordset clone (more about record sets in AVB202) Clone form’s recordset Use findfirst method with a search argument Set form bookmark to clone bookmark if record found
  • 44. 2.7 ..cont Add a text box for SKU to frmProduct Add a button Add code to button’s on-click event
  • 46. AVB201 – End of Course Thank You for Attending the Course And Wishing You a Happy VBA Programming !! NOTE: If interested, check our schedule for our Intermediate and Advanced VBA Courses.