AVB201.2 Microsoft Access VBA Module 2


Published on

Microsoft Access VBA course 2nd module.

Published in: Technology
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

AVB201.2 Microsoft Access VBA Module 2

  1. 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. 2. COURSE OUTLINE <ul><li>SESSION 1: Event driven Programming in Access </li></ul><ul><li>(3 hours). </li></ul><ul><li>SESSION 2: VBA Language Constructs and Programming Techniques (3 hours). </li></ul>
  3. 3. Session 2: VBA Language Constructs and Programming Techniques <ul><li>Making Decisions: If..Else.., Select Case.. </li></ul><ul><li>Making Repetitions simple: Do..Loop, For..Next </li></ul><ul><li>Calling Functions and Sub Procedures </li></ul><ul><li>Getting Interactive with Message Boxes. </li></ul><ul><li>Using VBA Editor for effective debugging. </li></ul><ul><li>Handling errors and missing data. </li></ul>
  4. 4. 2.1 Making Decisions: If..Else, Select..Case <ul><li>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: </li></ul><ul><li>A. If SomeVariable = 1 Then “do this” - short version </li></ul><ul><li>B. If SomeVariable = 1 Then - for making 2 choices </li></ul><ul><ul><li> Do this </li></ul></ul><ul><ul><li>Else </li></ul></ul><ul><ul><li> Do something else </li></ul></ul><ul><ul><li>End If </li></ul></ul>
  5. 5. 2.1 ..cont <ul><ul><li>Demonstration: See Print Product Dialog Form. </li></ul></ul>
  6. 6. ..cont <ul><li>C. There is a third form of IF which accommodates multiple conditions (more than 2): </li></ul><ul><li>If “SomeVariable = 1” Then </li></ul><ul><li>do this </li></ul><ul><li>ElseIf “SomeVariable = 2” Then </li></ul><ul><li>do that </li></ul><ul><li>Else </li></ul><ul><li>do third action </li></ul><ul><li>End If </li></ul>
  7. 7. ..cont <ul><li>C. There is a third form of IF which accommodates multiple conditions (more than 2): </li></ul><ul><li>There is no limit on how many “Else If” lines you can use. </li></ul><ul><li>Exercise: Use “if” to choose a day of the week and print the corresponding day name. i.e. 1 = Sunday, 2 = Monday. </li></ul><ul><li>Write a short sub function that accepts the day of the week. To save typing just do first few days. </li></ul>
  8. 8. ..cont
  9. 9. ..cont <ul><li>“ SomeVariable = 1” in the previous example can be replaced with any Boolean expression that evaluates to “True” or “False”. </li></ul><ul><li>Q: Do we all know Boolean expressions? </li></ul><ul><ul><li>If True, then statement following executes. </li></ul></ul><ul><ul><li>If False, the construct looks for another True condition or executes statement following Else, if no True is found. </li></ul></ul>
  10. 10. ..cont <ul><li>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!) </li></ul><ul><li>This last form of IF can often be replaced with the Select..Case statement, which can add to readability of the program (Select ahead). </li></ul>
  11. 11. Select .. Case <ul><li>“ 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: </li></ul><ul><li>Select Case “Test Expression” </li></ul><ul><li>Case 1 </li></ul><ul><li>action 1 </li></ul><ul><li>Case 2 </li></ul><ul><li>action 2 </li></ul><ul><li>Case Else </li></ul><ul><li>action 3 </li></ul><ul><li>End Select </li></ul>
  12. 12. ..cont <ul><li>NOTE: Which Case executes depends on whether “Test Expression” evaluates to 1,2, or something Else. </li></ul><ul><li>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. </li></ul>
  13. 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. 14. 2.2 Making Repetitions Simple: For..Next, Do..Loop <ul><li>Same piece of code often needs to execute more than once. There are two construct available to do just that: </li></ul><ul><li>For..Next and </li></ul><ul><li>Do..Loop. </li></ul>
  15. 15. ..cont <ul><li>Example which we used for demonstrating “Decisions” also demonstrates the use of For..Next statement. </li></ul><ul><li>For x = 1 to 5 [Step 2] </li></ul><ul><li>print report </li></ul><ul><li>Next x </li></ul><ul><li>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. </li></ul>
  16. 16. 2.2 Making Repetitions Simple: For..Next, Do..Loop
  17. 17. ..cont <ul><li>NOTES: </li></ul><ul><li>All values in the previous example, and in For .. Next loops in general, are variable and decided upon by the programmer or the user. </li></ul><ul><li>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..). </li></ul>
  18. 18. Do .. Loop <ul><li>X = 1 </li></ul><ul><li>DO </li></ul><ul><li>print report </li></ul><ul><li>x = x +1 </li></ul><ul><li>Loop While x <= 5 </li></ul><ul><li>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. </li></ul><ul><li>Exercise : Revise the previous code to use a do loop. </li></ul>
  19. 19. Do .. Loop
  20. 20. ..cont <ul><li>Do..Loop has several variants: </li></ul><ul><li>Do .. Loop [While | Until condition] </li></ul><ul><li>Do [While | Until condition] .. Loop </li></ul><ul><li>They differ in whether condition is checked at beginning or at end of the loop. </li></ul><ul><li>Though condition is optional it is a good idea to include it, if you ever want program to get out of the loop. </li></ul><ul><li>“ Exit Do” is another way to get out of the loop. It must be placed inside the loop. </li></ul><ul><li>“ Until” is just a different way of phrasing the condition. In previous example we could replace “While x < 5” with </li></ul><ul><li>“ Until x = 5”. </li></ul>
  21. 21. 2.3 Calling Functions and Sub Procedures. <ul><li>In well structured programs in one procedure or a function you often call one or more other procedures or functions. </li></ul><ul><li>Procedure calls can be as simple as stating the name of the procedure or you can use a “Call Procedure_ Name” form. </li></ul><ul><li>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. </li></ul>
  22. 22. 2.3 Calling Functions and Sub Procedures. <ul><li>Function calls need to be assigned to some variable since they always return a value. </li></ul><ul><ul><li>Ex: Answer = Function Name (). Use of MsgBox is an example of both. It can be called “standalone” or by returning a value. </li></ul></ul><ul><li>Functions are always called with parenthesis. No “Call” form is available. </li></ul>
  23. 23. 2.4 Getting Interactive with Message Boxes <ul><li>Message boxes display messages to the user whenever used as part of any procedure or other VBA code. </li></ul><ul><li>Syntax: MsgBox(prompt[, buttons],[, title][, helpfile, context]) </li></ul><ul><li>[, ] are optional. Only prompt is required. </li></ul><ul><li>In place of numbers use intrinsic constants to display </li></ul><ul><li>combination of buttons: vbOKOnly, vbOKCancel, vbAbortRetryIgnore, vbYesNoCancel, vbYesNo </li></ul><ul><li>Also vbCritical (x), vbQuestion (?), vbDefaultButton1, etc.. to add icons, set default button, etc.. For complete list, consult the online help or some other reference. </li></ul>
  24. 24. ..cont <ul><li>Ex: Confirm record delete with a dialogue </li></ul><ul><li>MsgBox(“Are you sure you want to delete this record?” vbYesNo, “Delete Confirmation”) </li></ul><ul><li>Hint: add your code to the on-click even “behind” the delete button. </li></ul>
  25. 25. ..cont
  26. 26. ..cont <ul><li>For setting buttons, default button, and the icon simultaneously, the constants must be added: </li></ul><ul><li>vbYesNo + vbDefaultButton2 + vbQuestion </li></ul><ul><li>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 !! </li></ul>
  27. 27. ..cont <ul><li>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. </li></ul><ul><li>Syntax: Answer = MsgBox(“Want to delete?”, vbYesNo) </li></ul><ul><li>If Answer = vbYes Then ..do this (ex: delete a record) </li></ul><ul><li>If Answer = vbNo Then ..do that (ex: move on) </li></ul><ul><li>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. </li></ul>
  28. 28. ..cont <ul><li>Proper use of Message Boxes in any Access application often makes a difference in how users perceive the “intuitiveness” of the application. </li></ul><ul><li>!! 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.. </li></ul><ul><li>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.. </li></ul>
  29. 29. 2.5 Using VBA Editor for Effective Debugging. <ul><li>You will on average spend 30% of your time writing a program on debugging. </li></ul><ul><li>Debugging, simply put, is a process of making your program run “Error Free”. </li></ul><ul><li>Errors come in two major types: Syntax and Logical. </li></ul>
  30. 30. ..cont <ul><li>SYNTAX ERRORS DEFINED: </li></ul><ul><li>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. </li></ul><ul><li>Syntax errors are easy to fix. </li></ul>
  31. 31. ..cont <ul><li>LOGICAL ERRORS DEFINED: </li></ul><ul><li>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. </li></ul><ul><li>VBA Editor, as well as VBA language, have extensive set of features to help you with the debugging process. </li></ul><ul><li>Use of word “bug” dates back to times when some roach literally shorted the computer circuits in early type computers. </li></ul>
  32. 32. Syntax Errors <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>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.. </li></ul>
  33. 33. Syntax Errors <ul><li>Demonstration: Go to standard module that we created and do some mistakes in written procedures and functions. </li></ul>
  34. 34. Logical Errors <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>Demo: Explore the Debug menu in VBA Editor. </li></ul>
  35. 35. ..cont (some useful commands) <ul><li>Step Into – run the next line of code. </li></ul><ul><li>Step Over – Run the next line of code and any code in any called procedures. </li></ul><ul><li>Step Out – Run the entire current procedure and then stop the next line in the original – calling procedure. </li></ul><ul><li>Run to Cursor – Move cursor to some line after current line and run all the code between. </li></ul><ul><li>Continue – Continues running the program until the next breakpoint. </li></ul><ul><li>Break – Stop the running program. Helps with endless loops. </li></ul><ul><li>Reset – Stops the error process and lets you restart it from any desired line of code. </li></ul>
  36. 36. 2.6 Handling Errors And Missing Data <ul><li>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”. </li></ul><ul><li>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... </li></ul>
  37. 37. ..cont <ul><li>“ 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. </li></ul><ul><li>“ 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. </li></ul><ul><li>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. </li></ul>
  38. 38. ..cont (example) <ul><ul><li>Private Sub cmdPrintDialog_Click() </li></ul></ul><ul><ul><li>‘ on error resume next </li></ul></ul><ul><ul><li>On Error GoTo Err_cmdPrintDialog_Click </li></ul></ul><ul><ul><li>‘ may trigger if report can’t be found </li></ul></ul><ul><ul><li>Dim stDocName As String </li></ul></ul><ul><ul><li>Dim stLinkCriteria As String </li></ul></ul><ul><ul><li>stDocName = &quot;frmPrintDialog&quot; </li></ul></ul><ul><ul><li>DoCmd.OpenForm stDocName, , , stLinkCriteria </li></ul></ul><ul><ul><li>Exit_cmdPrintDialog_Click: </li></ul></ul><ul><ul><li>Exit Sub </li></ul></ul><ul><ul><li>Err_cmdPrintDialog_Click: </li></ul></ul><ul><ul><li>MsgBox Err.Description </li></ul></ul><ul><ul><li>Resume Exit_cmdPrintDialog_Click </li></ul></ul><ul><ul><li>End Sub </li></ul></ul>
  39. 39. ..cont (example) <ul><ul><li>Exercise: add error processing code to Print Button on Products Form </li></ul></ul><ul><ul><li>Hint: Modify the code in the on click event. Change the name of the form to be launched to produce an error </li></ul></ul>
  40. 40. ..cont (example)
  41. 41. ..cont (example)
  42. 42. Handling Missing Data (Nulls) <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>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: </li></ul><ul><li>someVariable = Nz(someDBField) </li></ul>
  43. 43. 2.7 Finding a Record <ul><li>Can use recordset clone (more about record sets in AVB202) </li></ul><ul><ul><li>Clone form’s recordset </li></ul></ul><ul><ul><li>Use findfirst method with a search argument </li></ul></ul><ul><ul><li>Set form bookmark to clone bookmark if record found </li></ul></ul>
  44. 44. 2.7 ..cont <ul><li>Add a text box for SKU to frmProduct </li></ul><ul><li>Add a button </li></ul><ul><li>Add code to button’s on-click event </li></ul>
  45. 45. 2.7 ..cont
  46. 46. AVB201 – End of Course <ul><li>Thank You for Attending the Course And Wishing You a Happy VBA Programming !! </li></ul><ul><li>NOTE: If interested, check our schedule for our Intermediate and Advanced VBA Courses. </li></ul>