I am new to VB. I want to test some old VB code, but I need the ability to print to the console to be able to test certain values that are set in the code. How to print to the console from VB?
You can write run-time messages to the Output window using the Debug class or the Trace class, which are part of the System. Diagnostics class library. Use the Debug class if you only want output in the Debug version of your program. Use the Trace class if you want output in both the Debug and Release versions.
To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut Ctrl+Shift+D. The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.
Use debug.print. But there is no console on a VB6 application, that will print to the debug window.
This isn't expected to be the accepted answer because Debug.Print is the way to go for IDE testing.
However just to show how to use the standard I/O streams easily in VB6:
Option Explicit
'
'Reference to Microsoft Scripting Runtime.
'
Public SIn As Scripting.TextStream
Public SOut As Scripting.TextStream
'--- Only required for testing in IDE or Windows Subsystem ===
Private Declare Function AllocConsole Lib "kernel32" () As Long
Private Declare Function GetConsoleTitle Lib "kernel32" _
Alias "GetConsoleTitleA" ( _
ByVal lpConsoleTitle As String, _
ByVal nSize As Long) As Long
Private Declare Function FreeConsole Lib "kernel32" () As Long
Private Allocated As Boolean
Private Sub Setup()
Dim Title As String
Title = Space$(260)
If GetConsoleTitle(Title, 260) = 0 Then
AllocConsole
Allocated = True
End If
End Sub
Private Sub TearDown()
If Allocated Then
SOut.Write "Press enter to continue..."
SIn.ReadLine
FreeConsole
End If
End Sub
'--- End testing ---------------------------------------------
Private Sub Main()
Setup 'Omit for Console Subsystem.
With New Scripting.FileSystemObject
Set SIn = .GetStandardStream(StdIn)
Set SOut = .GetStandardStream(StdOut)
End With
SOut.WriteLine "Any output you want"
SOut.WriteLine "Goes here"
TearDown 'Omit for Console Subsystem.
End Sub
Note that very little of the code there is required for an actual Console program in VB6. The bulk of it is about allocating a Console window when the program is not running in the Console Subsystem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With