在 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