Wednesday, September 21, 2022

Debugging with Debug print method

Debug print is very useful for debugging instead of using message box because we can run without clicking OK button when we use message box. Debug print is utilizing immediate window below module under Visual Basic Editor (VBE) as below:


Base on above Table subject vs score we can print this value under immediate window as below:

The above example we use direct Debug.print value1,value2,value3,....

The purpose is to print value especially variables when our code is getting complicated and we wish to verify our code run without error later on.

Below example we use operator to connect or joint value1 & "-" & Value2 & "=" & Value3 but still using the same table above.

VBA Code:

Option Explicit
Sub PrintMethodExample()

    Dim i As Integer
    Dim StrSubject As String
    Dim IntScore As Integer
    With ActiveSheet
        i = 2
        Do
            'Assign Variables
            StrSubject = .Range("B" & i)
            IntScore = .Range("C" & i)
            
            'Print to immediate window for debugging
            Debug.Print i - 1 & "-" & StrSubject & "=" & IntScore
            
            'Reset Variables
            StrSubject = ""
            IntScore = 0
            i = i + 1
        Loop While .Range("A" & i) <> ""
    End With
    
End Sub

Result:


Note:
Normally when error occurred we put Debug.print before error line to verify which variables caused error. For example variable declare as integer but actual is long or double.

Microsoft Reference - Print Method

Practice makes perfect. Thank You.

No comments:

Post a Comment