在 VBA 的即时窗口中打印输出
    
    
            Glen Alfaro
    2023年1月30日
    
    VBA
    VBA Debugging
    
 
调试是计算机编程中开发软件最复杂的部分之一。好消息是 VBA 的创建者允许我们轻松调试 VBA 代码。
几个调试工具位于立即窗口、断点、步骤、变量观察器等位置,以帮助用户在程序开发的调试阶段。
在几个调试工具中,VBA 的 Immediate Window(VBA 的调试窗口)是一个流行的选项。它使用户能够在执行代码时打印、询问和运行方法和变量。
它允许用户立即获得有关变量和步骤的答案。它内置在 Visual Basic 编辑器中,具有不同的用途,在调试代码和显示代码结果时非常有用。
本教程将深入探讨使用 VBA 的即时窗口的用途和好处。
在 Excel VBA 中打开即时窗口
如果 VBA 中的 立即窗口 在 Visual Basic 编辑器中不可见,请按照以下步骤操作。
- 
打开 Excel 文件。
- 
从开发人员选项卡中,打开Visual Basic编辑器。
- 
从查看工具栏中,单击立即窗口。你也可以按 CTRL+G 来显示窗口。
你现在可以看到 Excel VBA 的即时窗口。
在 Excel VBA 的即时窗口中打印信息
该工具的用途之一是它能够打印字符串和值。在程序开发方面非常有帮助。它将允许你在更细粒度的级别上测试代码。
语法:
Debug.Print [Strings to print]
下面的代码演示了如何使用 Debug.Print 属性进行打印。
Sub PrintToImmediateWindow()
Debug.Print "This will be printed on the Immediate Window."
End Sub
PrintToImmediateWindow 输出:
Immediate Window:
This will be printed on the Immediate Window.
下面的代码块将演示打印变量的值。
Sub PrintVariableValue(toPrint As String)
Debug.Print (toPrint)
End Sub
Sub testPrint()
Call PrintVariableValue("testPrint123")
End Sub
testPrint 输出:
Immediate Window:
testPrint123
下面的代码块将打印 Success!在立即窗口中,当随机生成的数字可以被 3 整除时。
Sub StopWhenDivisible3()
Dim n As Integer
Dim isSuccess As Boolean
Do Until isSuccess = True
    n = Int((6 * Rnd) + 1)
    Debug.Print n & " is the current number"
    If n Mod 3 = 0 Then
        Debug.Print "Success!"
        isSuccess = True
    End If
Loop
End Sub
StopWhenDivisible3 输出:
Immediate Window:
2 is the current number
4 is the current number
4 is the current number
2 is the current number
2 is the current number
5 is the current number
5 is the current number
4 is the current number
6 is the current number
Success!
在 Excel VBA 中使用立即窗口询问有关活动工作簿的信息
立即窗口 功能之一是根据活动工作簿的当前信息返回答案。行中的第一个字符应该是问号 ? 启动询问命令。
下面的块将展示如何利用立即窗口来获取有关活动工作簿的信息。
要获取活动工作簿中工作表的编号:
Immediate Window
?Worksheets.Count
3
获取活动工作簿的名称:
Immediate Window:
?ActiveWorkbook.FullName
Book1
获取活动工作表的名称:
Immediate Window:
?ActiveSheet.Name
Sheet1
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe