1. Trang chủ
  2. » Công Nghệ Thông Tin

Access 2007 VBA Programmer’s Reference phần 2 docx

115 326 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 115
Dung lượng 0,9 MB

Nội dung

In addition to displaying the value of variables, you can also execute VBA commands in the Immediate window. Just eliminate the ? character and type the entire command, and then press Enter. Typing msg- box(“Tall or Grande?”) and pressing Enter displays the message shown in Figure 4-5. Figure 4-5 You can even perform calculations in the Immediate window such as: intTotalEmployees = intTempEmployees + intFullTimeEmployees. The Immediate window is also a powerful debugging tool for your applications. For more information about the Immediate window, see Chapter 8. Using the Immediate window along with other aspects of the VBA Editor detailed in this chapter, such as breakpoints and stepping through code, is the most generally accepted method of debugging your code. However, there are other options. One method that is often used by beginning developers is to place message box code throughout the code to test the values of selected variables or calculations. Although there is nothing technically wrong with this method, it can be messy and cumbersome. After all, when you’re done debugging the code, you still need to comment out or remove all of the message box calls. That can be a lot of unnecessary work. The Debug.Print Statement As you already know, the ? character is short for Debug.Print, and you’ve seen how easy it is to use both commands directly in the Immediate window. That’s not the only place you can use Debug.Print statements, The following code illustrates how Debug.Print can be used within a module, so you can imagine how it can be helpful for testing and debugging. Sub FunWithStringsAndNumbers() Dim strBikes As String Dim strCost As String Dim strCustomerName As String Dim intBikes As Integer Dim curCost As Currency strBikes = “5” strCost = “100” strCustomerName = “The “”W”“ Hotel, New York City” intBikes = 5 curCost = 100 Debug.Print strBikes + strCost Debug.Print intBikes + curCost Debug.Print strCustomerName End Sub 73 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 73 This code produces the following results in the Immediate window: 5100 105 The “W” Hotel, New York City You can use the Debug.Print statement within any procedure to display results of calculations or val- ues of variables in the Immediate window. That’s a quick way to confirm that your code is achieving the desired results. The Debug.Assert Statement You can just as easily type Debug.Assert in the Immediate window. This option conditionally suspends execution of code at the line where Debug.Assert appears. For example, the following code uses the Debug.Assert statement to stop code execution when a specific condition is met: Option Compare Database Private blnUnderBudget As Boolean Const curBudget = 1000 Private Sub GoShopping() Dim intSuits As Integer Dim curSuitPrice As Currency Dim curTotalPrice As Currency Dim i as Integer curSuitPrice = 100 intSuits = InputBox(“Enter the desired number of suits”, “Suits”) For i=1To intSuits curTotalPrice = curTotalPrice + curSuitPrice If curTotalPrice > curBudget Then blnUnderBudget = False Else blnUnderBudget = True End If Debug.Assert blnUnderBudget Next End Sub The code breaks every time you go over budget on your shopping trip. You can use this statement when testing for specific conditions within your code. Although Debug.Assert is a good debugging tool, you probably won’t ever use it in live code because it’s a rather abrupt way to stop an application. The user would get no warning and because the code stops, you do not get to provide him with a friendly mes- sage or explanation. Breakpoints Breakpoints are simply places in your code that pause execution of code. For example, to check the value of a variable curTotalCost midway through the following procedure, you’d need to use the Debug.Print statement (as in the following code) or set a breakpoint. 74 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 74 Sub HowMuchCanWeSpend() Dim curTotalPrice As Currency Dim curUnitPrice As Currency Dim intNumSocks As Integer Dim i As Integer curUnitPrice = 3.5 intNumSocks = InputBox( _ “Please enter the number of pairs of socks youwant.”, _ “Pairs of Socks”) For i=1 To intNumSocks curTotalPrice = curTotalPrice + curUnitPrice Next Debug.Print curTotalPrice End Sub This code prints in the Immediate window the amount you’ll spend for the total sock purchase. That’s great, but what if you want to see how your total expense is adding up as you go? You can certainly add a Debug.Print statement within the For Next loop, but you can also set a breakpoint anywhere in the procedure. Once the breakpoint is reached, you can use the Immediate window to check the value of your variables. You can set a breakpoint on any line of code except for Dim statements and comments. The simplest way to set a breakpoint is to click in the left margin of the Code window. A brick-colored dot appears in the margin and the corresponding line of code is highlighted. To clear a breakpoint, click the left margin again in the same spot. You can also set and clear breakpoints by placing your cursor in the desired line of code and selecting Debug ➪ Toggle Breakpoint or pressing F9. When you run the code, every time the breakpoint is reached, code execution stops and VBA waits for you to decide what to do next. You can choose from the following options: ❑ Check the value of variables in the Immediate window. When your code reaches a breakpoint, the value of all variables is retained. You can check the value of any variable by using the Debug.Print statement or the ? character within the Immediate window. ❑ Use your mouse to hover over any variable in the current procedure. The value of the variable is displayed close to the mouse cursor. ❑ Press F5 or select Run ➪ Continue to continue code execution. Execution proceeds until the next breakpoint or the end of the procedure. When VBA encounters a breakpoint, it pauses execution immediately before the line of code is executed. The line of code that contains the breakpoint is not executed unless or until you choose to step through the code using the F8 key. Stepping Through Code In most cases, you design code to run with little or no user intervention. However, when you’re testing code, sometimes it is helpful to do more than insert a couple of breakpoints or include some Debug.Print statements. If you’re running code with several variable changes or some intricate loop- ing, it can sometimes be helpful to step through the code line by line. Doing this allows you to watch the value of variables after each line of code is executed. This can help you pinpoint any errors or mistakes in the logic of the code. 75 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 75 To step through your code, place the cursor at the point that you want to initiate the process and press F8 to begin the procedure (you can also press F8 after the code has entered break mode to step through the remaining code). When you press F8 to begin code execution, the name of the sub or function is highlighted in yellow. Subsequent presses of the F8 key move execution from line to line, highlighting the next executable line in yellow. Comment lines and Dim statements are skipped when stepping through code. As you press F8, the highlighted line is executed. Stepping through code is an important tool so it is worth reiterating how the process works. The first instance of F8 highlights the next executable code; the subsequent instance of F8 executes the high- lighted code. If nothing is highlighted, F8 highlights code; if something is highlighted, F8 runs it. If the current procedure calls another sub or function, F8 will also execute the called procedure line by line. If you’re confident that the called procedure doesn’t contain any errors, you can execute the entire called procedure and then return to line-by-line execution of the calling procedure. This is called stepping over the procedure, and it is done by pressing Shift+F8. Stepping over the called procedure executes the entire procedure and then returns to the calling procedure, to proceed with code execution one step at a time. If you’re within a called procedure, you can press Ctrl+Shift+F8 to step out of the current proce- dure. What’s the difference between stepping over and stepping out of the procedure? If you’re already in the called procedure, the two are exactly the same. But here’s an example that illustrates the difference and gives you some practice with code. Assume you’re stepping through the following code (which is in the Chapter 4 download material): Option Compare Database Private blnUnderBudget As Boolean Const curBudget = 1000 Private Sub GoShopping() Dim intSuits As Integer Dim curSuitPrice As Currency Dim curTotalPrice As Currency curSuitPrice = 100 intSuits = InputBox(“Enter the desired number of suits”, “Suits”) For i=1To intSuits curTotalPrice = curTotalPrice + curSuitPrice If curTotalPrice > curBudget Then blnUnderBudget = False Else blnUnderBudget = True End If Next If blnUnderBudget = False Then OverBudget End If End Sub Private Sub OverBudget() Debug.Print “You’ve gone over budget.” Debug.Print “You need to work some overtime.” Debug.Print “Remember to pay your taxes.” End Sub 76 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 76 Use the F8 key to step through the code until you reach the last If Then loop (If blnUnderBudget = False Then ). When the OverBudget line is highlighted in yellow (meaning it hasn’t yet been executed), stepping over the OverBudget procedure returns execution to the line after the OverBudget call (in this case the End If line). If you step out of the procedure, the OverBudget procedure runs, and your code returns to the GoShopping procedure and completes the procedure. If, however, you use the F8 key to step through your code until you reach the first line of the OverBudget procedure, stepping out of the procedure returns you to the line after the OverBudget call (the End If line). Use the following table as a cheat sheet and create some simple procedures to test the various debugging techniques shown in this chapter. Debugging Technique Description Keyboard Shortcut Step Into F8 Step Over Shift+F8 Step Out Ctrl+Shift+F8 Call Stack The Call Stack dialog box displays a list of the current active procedure(s) when you are stepping through code. An active procedure is one that is started but not completed. You can access the Call Stack dialog box in several ways, including from the menu bar (View the Call Stack) or by pressing Ctrl+L. Because the call stack is available only in break mode, access to the call stack is often grayed out (disabled). The Call Stack dialog box is not a window and therefore cannot be left open when stepping through code. It is opened and closed at each active procedure. You gain the most benefit from the Call Stack dialog box when one procedure is calling another or if you have nested procedures, whether they are in the same module or being called by other modules. If another procedure is called from the first procedure, the dialog box displays the new procedure at the top of the list with the original (calling) procedure under it, thus stacking them. Figure 4-6 illustrates this stacking process. OverBudget was called by GoShopping, so OverBudget is listed first, and it is high- lighted because it is the procedure being run. Once a procedure is finished, it is removed from the stack. In this case, after OverBudget is run, GoShopping will be the only procedure in the stack. VBA executes the remainder of the current procedure. If executed within the second procedure, the entire second procedure is executed and execution returns to first pro- cedure on the line following the line that called the second procedure. Executes code one line at a time within the current procedure. If a second procedure is called from within the first, the entire sec- ond procedure is executed at once. Executes the next line of code in your pro- cedure (highlights line in yellow). 77 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 77 Figure 4-6 When stepping through multiple procedures from different modules, or even from the same module, it can be a little confusing as to where a particular procedure is being called. To help find the start of the any active procedure in the call stack, highlight the active (top) procedure in the list and either double-click the item or click the Show button. In the current example, the call stack was opened when OverBudget was called, so two procedures are listed. To find out what line called OverBudget, you can double-click on GoShopping, the calling procedure. This puts a green pointer at the line in GoShopping that called OverBudget. Figure 4-7 shows OverBudget still highlighted in yellow, because that’s the current point in stepping through the code, and the green pointer at the call to OverBudget. Figure 4-7 78 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 78 As you might imagine, the call stack is helpful when you are working with multiple procedures and try- ing to determine where errant data may be originating. It is also a handy tool when working with some- one else’s application or even modules. Run to Cursor Many times when you’re executing code, you don’t want to run every line of code line by line, but exe- cuting the entire procedure at once doesn’t help you isolate the problem. And it is very tedious to exe- cute every line of the loop each time a long loop needs to run. For example, consider the following code: Sub CoffeeTime() Dim curLatteAllowance As Currency Dim curLattePrice As Currency Dim intNumLattes As Integer Dim curTotalExpenses As Currency curLattePrice = 3.5 curLatteAllowance = InputBox( _ “Enter the amount of money you have for lattes.”, _ “Latte Allowance”) While curTotalExpenses < curLatteAllowance intNumLattes = intNumLattes + 1 curTotalExpenses = curTotalExpenses + curLattePrice Wend Debug.Print intNumLattes MsgBox “You can purchase “ & intNumLattes & “ lattes.”, _ vbOkOnly, “Total Lattes” End Sub If you have $350 to spend on lattes, the While Wend loop will run 100 times. Pressing F8 to step through that long of a loop can be quite tiresome. Thankfully, there is a shortcut. If you’re not worried that the loop is producing incorrect data, you can place your cursor in the Debug.Print intNumLattes line and press Ctrl+F8. Your procedure will run until it reaches the Debug.Print line, where it halts and is highlighted. You can then press F8 to execute just the highlighted line of code or press F5 to continue execution until the end of the procedure. Locals Window Sometimes it can be utterly mind-numbing to test the value of every variable when your code enters break mode. If you’re stepping through code and need to test the value of seven different variables every step of the way, that’s a lot of Debug.Print statements to keep track of in the Immediate window. You can use the Locals window to display all the variables in a procedure and their values. You can watch the variable values change as you step through the code. To display the Locals window, select View ➪ Locals Window. Figure 4-8 shows the Locals window while stepping through a procedure. As you step through the procedure, the Locals window shows you the up-to-date values of all variables. The Locals window is not emptied until the last line of code has been executed. In this case, you’d see a message box stating, “You can purchase 100 lattes.” 79 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 79 Figure 4-8 Watch Window The last debugging tool you’ll examine in this chapter is the Watch window, which enables you to watch a variable within your procedure. When the value of the variable changes or when the variable is True, your code enters break mode. To open the Watch window, select View ➪ Watch Window. To see how the Watch window works, use WatchGoShoppingSuits, a modified version of the GoShopping mod- ule. Recall that it uses a Boolean expression and message box to let you know if you’re over budget. Add a watch on the blnOverBudget.Start by right-clicking in the Watch window and choosing Add Watch. The Add Watch dialog box opens (see Figure 4-9). Enter blnOverBudget in the Expression text box. In the Watch Type, the default is to Watch Expression, although you could choose Break When Value is True, or Break When Value Changes. For this example, choose Break When Value Is True, and then click OK to save your watch. When you run the SteppingThroughCodeGoShopping2 procedure, the procedure enters break mode when the value of blnOverBudget becomes true. As soon as the loop executes for the eleventh time, the watch expression is triggered and the code enters break mode. If you choose to simply watch the expression (rather than break), the Watch window behaves almost exactly like the Locals window except that only watched variables are shown. 80 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 80 Figure 4-9 If you have a rather long loop to execute and you no longer need your watch, you can delete it while your code is in break mode. Simply right-click the watch and select Delete Watch. You can then press F5 to continue code execution. Option Compare Database Private blnOverBudget As Boolean Const curBudget = 1000 Private Sub GoShoppingSuits() Dim intSuits As Integer Dim curSuitPrice As Currency Dim curTotalPrice As Currency curSuitPrice = 100 intSuits = InputBox(“Enter the desired number of suits”, “Suits”) For i=1 To intSuits curTotalPrice = curTotalPrice + curSuitPrice If curTotalPrice > curBudget Then blnOverBudget = True Else blnOverBudget = False End If 81 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 81 Next If blnOverBudget = True Then Msgbox “You’re over budget!”, vbExclamation, “Over Budget” End If End Sub A shortcut for adding a watch is to right-click the expression and select Add Watch. The expression is filled in automatically, so you avoid the risk of typos. On-the-Fly Changes Every once in a while your code will halt because of an error or a breakpoint. The VBA Editor will dis- play the problem line or breakpoint line with an arrow pointing to it. You may discover the problem on that line, make the appropriate changes, and find that the line executes correctly. You can test this simply by pressing the F8 key and stepping through that line of code. If you realize that the problem is several lines before the current location, you can make the correction and easily restart the code from a different location. Just click on the original arrow (pointer) and drag it to the line where you want to start execut- ing the code. Be aware that depending on what code was executed, you may not get valid results, particularly if it is dependent on earlier code or values. So if you think you’ve corrected the problem but it still isn’t dis- playing the expected values, it would be prudent to rerun the entire module or function. Also, code changes during execution may not always be saved when the program ends. Although all the scenarios that might trigger that can’t be identified, you can expect it to happen if the code causes the application to shut down. The logic is that you would not want to save modifications that caused the appli- cation to crash. But because it can be frustrating to lose other, desirable modifications, it’s prudent to save your changes as you go, as usual. Summary This chapter explored the VBA Editor, and showed you how to use some of the tools and numerous win- dows that it provides. As you work with applications and projects, you will find the Immediate window to be an invaluable tool. Understanding the fundamentals will make it a lot easier and more fun to go through the rest of the book. There are lots of new features and tools to create powerful and professional forms and reports and to make it a breeze to work with other applications. Remember that you can download the code, databases, and other materials from the book’s website. At a minimum, the sample files make it easier to follow along; plus, they’ll help you avoid the potential for typos or misreading characters or formatting. 82 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12:24 AM Page 82 [...]... Approximately – 922 ,337 ,20 3,685,477.5808 to 922 ,337 ,20 3,685,477.5807 Decimal* 14 bytes With no decimal places, the range is +/–79 ,22 8,1 62, 514 ,26 4,337,593,543,950, 335 or with decimal places, the range is +/– 1E 28 (one to the 28 th power) The smallest possible non-zero number is 0.000,000,000,000,000,000,000,000,000,1 written +/–1E -28 Date 8 bytes 1/1/100 to 12/ 31/9999 GUID 16 bytes _2, 147,483,648 to 2, 147,483,647... 47033c05.qxd:WroxProgRef 3/30/07 12: 24 AM Page 86 Chapter 5: VBA Basics Data Type Size in Memory Possible Values Byte 1 byte 0 to 25 5 Boolean 2 bytes True or False Integer 2 bytes – 32, 768 to 32, 767 Long (long integer) 4 bytes 2, 147,483,648 to 2, 147,483,647 Single (single-precision real) 4 bytes Approximately –3.4E38 to 3.4E38 Double (double-precision real) 8 bytes Approximately –1.8E308 to 4.9E 324 Currency (scaled... with dates Different countries represent dates in various formats For example, the date 4/1 /20 07 could represent either April 1, 20 07, or January 4, 20 07, depending on the region of the world in which you live To work 88 47033c05.qxd:WroxProgRef 3/30/07 12: 24 AM Page 89 Chapter 5: VBA Basics around this challenge, VBA has a nifty way of dealing with dates All dates are represented as a floatingpoint number... discussion of how to set and use references.) Every time you set a reference to another application’s object library, you have access to all objects within that library An object is generally thought of as a 47033c05.qxd:WroxProgRef 3/30/07 12: 24 AM Page 84 Chapter 5: VBA Basics physical thing For example, if you were to set a reference to a car’s object library, you could access all the car’s objects,...47033c05.qxd:WroxProgRef 3/30/07 12: 24 AM Page 83 VBA Basics Now that you know a bit about automating Access, using macros, and how VBA fits into the Access automation picture, you’re almost ready to write some code The next step is to review some VBA basics For experienced programmers, this chapter is unnecessary; however, if you’re just delving into VBA from another programming language or... Notice that the VBA data types are similar to the data types in an Access table The major differences between Access data types and VBA data types are that there is no equivalent to the variant or object data types in Access data types, and the Access Number data type has a field size property that enables you to specify the field as Byte, Integer, Long, Single, Decimal, or Double Access has one other... the date, an initial date is needed for calculations Access uses December 30, 1899 as day 0, so April 1, 20 07 would be represented as 39173, so it follows that 6:00 P.M on that date is represented as 39173.75 Rest assured that when you’re working with dates in VBA, you do not have to perform conversions between 39173.75 and April 1, 20 07, 6:00 P.M VBA is aware of the regional settings specified in the... print phrase will appear in the Immediate window, as shown in the following example: Sub CompareNulls2() Dim varValue1 As Variant 93 47033c05.qxd:WroxProgRef 3/30/07 12: 24 AM Page 94 Chapter 5: VBA Basics Dim varValue2 As Variant varValue1 = Null varValue2 = Null If IsNull(varValue1) And IsNull(varValue2) Then Debug.Print “Both variables are Null” End If End Sub This code sample prints the phrase in... basic VBA programming objects, learn about variables and how to declare them, and review some additional VBA structures that you’ll use in your code Along the way, you’ll build a few procedures, and you will soon gain the skill and confidence to modify those procedures and to create your own VBA Objects You can’t program in VBA without understanding how the various VBA components work together All VBA. .. assign a value of April 1, 20 07, to the variable dtInitialDate, use the following code: dtInitialDate = #04/01 /20 07# That ensures that VBA will recognize the date properly no matter what your regional settings are However, if you’re in a region of the world that enters dates with d/m/yyyy, you’ll need to enter the literal date in the format m/d/yyyy when using this method Otherwise, VBA won’t recognize it . integer) 8 bytes Approximately – 922 ,337 ,20 3,685,477.5808 to 922 ,337 ,20 3,685,477.5807. Decimal* 14 bytes With no decimal places, the range is +/–79 ,22 8,1 62, 514 ,26 4,337,593,543,950, 335 or with. formatting. 82 Chapter 4: Using the VBA Editor 47033c04.qxd:WroxProgRef 3/30/07 12: 24 AM Page 82 VBA Basics Now that you know a bit about automating Access, using macros, and how VBA fits into the Access. 4/1 /20 07 could represent either April 1, 20 07, or January 4, 20 07, depending on the region of the world in which you live. To work 88 Chapter 5: VBA Basics 47033c05.qxd:WroxProgRef 3/30/07 12: 24

Ngày đăng: 09/08/2014, 12:22

TỪ KHÓA LIÊN QUAN