vba程序的vb6封装_调试VBA和VB6应用程序

vba程序的vb6封装

The debugging module can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.

There is also a companion Debug Toolbar that looks like the following and that toolbar will be the focus of this tutorial:

If you can't find that toolbar then you can add it to the menus by pulling down the View menu item, clicking Toolbars, and checking Debug.

Components of the Debug Toolbar

They are (in order)

o Continue (toggle)

o继续（切换）

o Break

o休息

o End

o结束

o Toggle Breakpoint

o切换断点

o Step Into

o进入

o Step Over

o越过

o Step Out

o走出

o Locals Window

o当地窗口

o Immediate Window

o立即窗口

o Watch Window

o观察窗

o Quick Watch

o快速观看

o Call Stack

o呼叫堆栈

The following is an explanation of what each button does. (I've changed the order a bit.)

Start/Continue (toggle)

Availability: Design time and when in break mode

Shortcut: F5

Clicking Start not surprisingly starts your program running just likes F5 does. After Start is clicked it is disabled.

Break

Availability: Run time only

Shortcut: CTRL+BREAK

Once your program has started, and, for example, the main form has loaded and it is ready for interaction with the user, pressing the Break button pauses the execution of the program and takes you to the edit window for the form. Pressing the button also has the effect of enabling the Start button and toggling it to Continue. At this point, you can do things like adding or changing code in the Click event of a command button. Pressing the Continue button takes you back to Run mode where you can now click the command button to see the effect of your change. The breaking/changing code/continuing/testing code cycle can, of course, be repeated as many times as needed.

Immediate Window

Availability: At all times but it is read-only at run time

Shortcut: CTRL+G

The Immediate Window is one of three debugging windows that allow you to monitor the values of expressions and variables while stepping through the statements in your application. The other two windows (which I'll discuss later) are the Watch window and the Locals window.

There are at least four very useful things that you can do with the Immediate Window.

1) Display the results of Debug.Print statements

1） 显示Debug.Print语句的结果

As an example let's assume you have the following code in your command button.

Private Sub Command1_Click()

Dim lngCounter As Long

For lngCounter = 1 To 3
Debug.Print lngCounter * 20
Next

End Sub


When you click the command button, the Debug.Print statements will cause the value of lngCounter * 20 to be printed to the Immediate Window so if you then click the Immediate Window button you will see the following.

2) Check the value of variables

2） 检查变量的值

While you are in break mode you can display the values of the global variables in your form. For example, if you have a Private intMyInt As Integer statement you can see what the value of intMyInt is by typing ?intMyInt in the Immediate Window and pressing return. The same thing can be accomplished by typing print intMyInt. The values of such things as command button and label captions, textbox text, etc. can be displayed as well. In addition, you can see the value of variables in a Sub or Function if you are at a break point but more about that later.

3) Change the value of variables and properties

3） 更改变量和属性的值

If you type something like intMyInt = 7 (note that you don't use the question mark) VB will change the value as requested and you can continue execution using that new value. This can be a big time-saver when debugging. A big time-saver when designing a form is that you can, for example, change the value of the Left property of a command button and immediately see what it looks like on the form. If it still needs adjusting you can change it again and again if necessary until you get it right. In this case, you will have to record that value in the IDE, but it is much better than having to repetitively change the value, run the program, see how it looks, stop, change the value, run the program, etc. until you get it right.

4) Run code

4） 运行代码

It's nice to be able to display the values of variables in the Immediate Window but if you have a set of variables you need to display and you need to do it more than once, retyping them can be tedious. Fortunately, there's a better way. You can simply create a Sub that you run from the Immediate Window! As an example let's assume that you have 3 variables that are involved in your debugging efforts. You would then create a Sub that looks something like this.

Private Sub DisplayDebugValues()
Debug.Print "The value of intMyInt is " & intMyInt
Debug.Print "The value of lngCounter is " & lngCounter
Debug.Print "The value of strSomeThing is " & strSomeThing
End Sub


Once you have that Sub you can display them any time you are in break mode by simply typing the name of the Sub in the Immediate Window, pressing Enter, and the three values will be displayed. Note that in order for this to work, the variables need to be global in scope. In other words, they need to be defined as Public in a module or in the Declarations section of a form or sheet.

Toggle Breakpoint

Availability: At design time and when in break mode

Shortcut: F9

A breakpoint is a place at which the program will pause until you manually let it resume.  To set a breakpoint you can either place the cursor on the line where you want the code to pause and then press F9 or, more simply, just click in the margin of that line. When you do either of those things VB places a red bullet in the margin and also highlights the line in red. Here is an example where a breakpoint has been placed on a line.

If you then run the program and the breakpoint is reached, VB will highlight the line's code in yellow and then wait there for you to do whatever you want. One of the things that you might want to do is to check the value of variables in the Sub or Function (these are called Local variables) and there are several ways to do that while the code in the Sub or Function is paused. You can hover the mouse over a variable and VB will pop up a little box that shows the variable name and its value, or you can bring up the Immediate Window as we discussed previously, or you can highlight any valid expression and click the Quick Watch window or you can click the Locals Window. The latter two will be described later.

I should mention here that while F9 will toggle a breakpoint on and off, CTRL+SHIFT+F9 will turn all breakpoints off.

Quick Watch

Availability: Always available but only useful when in break mode

Shortcut: SHIFT+F9

As mentioned previously if you highlight a variable or a valid expression, clicking the Quick Watch button will show you the value. Here's an example where I've done that with txtSquare(intSquare).Text (which is a valid expression) and you can see that the value is Y. Clicking the Add button allows you to add a watch, but more about that later.

Locals Window

Availability: Always available but only useful when in break mode

Shortcut: (None)

Here's what you would see at the same point in the program if you opened the Locals window. I've expanded the information for the form (referred to as Me) and the information for the Controls.Item6.

Step Into

Availability: Design time and when in break mode

Shortcut: F8

Step Into allows you to follow the execution of your program line by line as VB executes it. If you press F8 at Design Time the program will start just like it would if you pressed F5 (Start), except that after it is started VB will pause the program just before the first executable line and it will highlight that first executable line in yellow. It will also place a yellow arrow in the left-hand margin. When you press F8 while in break mode VB executes the current line and then pauses at the next line. In either case, you can step through the whole program if you desire by repetitively pressing F8. Note that at any time during that process you can use the Quick Watch, Immediate or Locals window as described above.

One very useful feature that is available while stepping through the code is the ability to drag the yellow arrow to any executable line of code, thus allowing you to skip or repeat lines.

Step Over

Availability: Design time and when in break mode

Shortcut: SHIFT+F8

Step Over is similar to Step Into except that as its name implies it will step over or skip the current line. Note that it doesn't skip the execution of the line, only the stepping through. In other words, if the current line is a call to a long Sub that you don't really care about, stepping over will execute the call and then pause at the line following the call.

Step Out

Availability: Design time and when in break mode

Shortcut: CTRL+SHIFT+F8

If you are in the same long sub as mentioned above, pressing Step Out will leave that sub and pause at the next executable line. Just like Step Into, Step Out doesn't skip the execution of the rest of the sub, only your viewing of it.

Call Stack

Availability: In break mode

Shortcut: CTRL+L

The Call Stack displays a list of all active procedure calls. An active procedure is the Subs and Functions in the application that were started but not yet completed. In the following trivial example, a breakpoint was placed on last in a string of Subs and the Call Stack shows the order of the calls (bottom-up) that got us to the breakpoint. All the subs are shown in the list because none of them have actually finished yet. If you were to step through the code from this point you would see the subs, starting with Sub5, disappear one by one from the Call Stack as the code progressed back up the chain exiting and thus finishing the subs. Finally, if you double-click on one of the entries or click on it and then press the Show button you will be taken to that procedure and a green triangle will be placed in the left-hand margin showing the next procedure in the stack.

Watch Window

Availability: At all times

Shortcut: (None)

We now (finally) come to what I consider the heart of debugging; the Watch Window.

Earlier I talked about the Quick Watch window which allows you to see the values of variables or valid expressions when you are at a breakpoint. (Note that from here on when I refer to "expression" that I mean both valid expressions and variables.) The weak point of that method is that you have to set the breakpoint before you are able to use the window. A watch, on the other hand, allows you to set up an expression that VB watches for you as the program runs and optionally pauses the program when a condition you state occurs. In other words, you don't have to know where to put the breakpoint - VB does it for you!

You can create a watch by

o Clicking the Watch Window button, right-clicking on it and choosing Add watch... or

o单击“监视窗口”按钮，右键单击它，然后选择“添加监视...”或

o Clicking the Debug|Add Watch... menu item or

o单击“调试|添加监视...”菜单项，或

o Highlighting an expression, right-clicking, and choosing Add Watch...

o突出显示一个表达式，单击鼠标右键，然后选择“添加监视” ...

When you do one of those things you will be presented with the Add watch window which looks like this.

Let's now examine the three parts of that window.

1) Expression

1）表达

The Expression is the expression you are interested in. It can be a single variable name like intMyInt or a simple expression like intMyInt = 5 or a complex expression like intMyInt > 5 and SomeOtherVar = 37 and bOK = True. Note that capitalization doesn't count and that while there may be a limit to the complexity or length of the expression, I haven't run across either.

2) Context

2）上下文

The Context choices defines for VB where you would like it to watch the Expression, and as you see above the default is all procedures in all modules - in other words, the whole program. You will notice I'm sure that the Context choices are two drop-down items and, for example, if you click on the Module drop-down, you will see something like the following where all the modules in the program are listed.

If you have selected a module then clicking on Procedure will display the procedures contained in that module.

2) Watch Type

2）手表类型

There are three Watch Types and you can choose one of them.

Watch Expression 手表表情

In order to use Watch Expression effectively, you need to have a breakpoint set. Once the watch is created and the breakpoint is reached, clicking on the Watch window button will display something like the following. Note that the Watch Window is dock-able and once docked there's no need to click on it in order for its contents to be seen.

The eyeglasses symbol under Expression tells you that it's a Watch Expression, and the little box with the plus sign indicates that txtSquare has more than one property that we can look at. Clicking on the plus sign will expand the result to show you all the properties and their values. Note that if the Watch Expression had been txtSquare(Index).Text instead of just txtSquare(Index) that there would be no plus sign since we were specific about the property we were interested in. The other things displayed in the widow are pretty self-explanatory but I'll mention them for completeness. Value is the value of the expression, Type is the type of item you are looking at, and Context is the scope of the Watch Expression.

Expression下的眼镜符号告诉您这是一个Watch Expression，带有加号的小框表示txtSquare具有多个可以查看的属性。 单击加号将展开结果，以向您显示所有属性及其值。 请注意，如果Watch Expression是txtSquare（Index）.Text而不是txtSquare（Index），则由于我们对所关注的属性是特定的，因此不会有加号。寡妇中显示的其他内容都是很简单的-不言而喻，但为了完整起见，我会提及它们。 值是表达式的值，类型是您要查看的项的类型，上下文是监视表达式的范围。

This is probably as good a place as any to mention that once you have a Watch Expression you can change or delete any watch by way of the Debug|Edit Watch menu item.

Break When value Is True 值为真时中断

Break When Value Changes 价值变化时打破

As far as I know, there is no limit to the number of watches you can have and I could add a third watch with mstrLastPlayer as the Expression and Break When Value Changes selected. That type of watch is indicated in the window by a yellow-triangle-in-hand symbol and I'm sure you have already figured out that that watch would pause the program any time mstrLastPlayer changed value.

Unfortunately watches only exist as long as the particular project is open and can not be saved. Also, a watch that you are no longer interested in can get in your way by, for example, continually pausing the program when one of the "Break" type watches becomes true or its value changes. You can, of course, get around that by deleting the particular watch or you can simply edit the watch by adding say, an "X" at the front of the expression thereby making it invalid. Once it is invalid VB will ignore it but not delete it. Later on, if you like you can remove the "X" which will reactivate it.

Debug Is A Great Tool

Over the years I've found that Debug has been an invaluable asset in helping me track down the bugs that slip into my programs, and I hope that this tutorial has given you enough of an understanding of it so that you will feel comfortable using it to track down your errors.

To give you a start at using it I've attached a version of a Tic-Tac-Toe game I wrote that has a bug. What happens is that the second time either "X" or "O" wins a game their total shows as 3 rather than 2. You may well be able to find the bug by just visually inspecting the program but I encourage you to try to find it using the tools provided by Debug.

Tic-Tac-Toe-Bug.zip

If you find that this article has been helpful, please click the “thumb’s up” button below. Doing so lets me know what is valuable for EE members and provides direction for future articles. It also provides me with positive feedback in the form of a few points. Thanks!

vba程序的vb6封装

• 0
点赞
• 0
评论
• 1
收藏
• 一键三连
• 扫一扫，分享海报

09-18

11-01
01-15
01-01
11-18 1114
10-14
03-16 8439
08-19 1178
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。