Microsoft Office Tutorials and References
In Depth Information
Example 4-1. A Simple Program to Trace
Example 4-1. A Simple Program to Trace
Sub Test()
Dim ws As Worksheet
Set ws = ActiveSheet
' Insert a value into cell A1
ws.Cells(1, 1).Value = "sample"
' Make it bold
ws.Cells(1, 1).Font.Bold = True
' Copy cell
ws.Cells(1, 1).Copy
' Paste value only
ws.Cells(2, 1).PasteSpecial Paste:=xlValues
End Sub
Make sure that an empty worksheet is active in Excel. Switch to the VBA IDE and place the
insertion point somewhere in the code. Then hit the F8 key once, which starts the tracing process.
(You can also choose Step Into from the Debug menu.)
Continue striking the F8 key, pausing between keystrokes to view the effect of each instruction in
the Excel window. (You can toggle between Excel and the IDE using Alt-F11.) As you trace
through this code, you will see the word "sample" entered into cell A1 of the active worksheet,
changed to appear in boldface, copied to the Clipboard, and pasted as normal text into the cell A2.
Then you can begin to see what Excel VBA programming is all about!
Let us discuss some of the tools that Excel provides for debugging code.
4.6.1 Tracing
The process of executing code one line at a time, as we did in the previous example, is referred to
as tracing or code stepping . Excel provides three options related to tracing: stepping into, stepping
over, and stepping out of. The difference between these methods refers to handling calls to other
procedures.
To illustrate the difference, consider the code shown in Example 4-2 . In ProcedureA , the first
line of code sets the value of cell A1 of the active worksheet. The second line calls ProcedureB
and the third line boldfaces the contents of the cell. ProcedureB simply changes the size and
name of the font used in cell A1. Don't worry about the exact syntax of this code. The important
thing to notice is that the second line of ProcedureA calls ProcedureB .
Example 4-2. Sample Code for Tracing Methods
Sub ProcedureA()
ActiveSheet.Cells(1, 1).Value = "sample"
Call ProcedureB
ActiveSheet.Cells(1, 1).Font.Bold = True
End Sub
Sub ProcedureB()
ActiveSheet.Cells(1, 1).Font.Size = 24
ActiveSheet.Cells(1, 1).Font.Name = "Arial"
End Sub
 
 
Search JabSto ::




Custom Search