0

How can I open a console window from Excel?

I want to display debug information.

I already log to a UserForm, the Immediate window and files.

I tried using AllocConsole, but it fails with error 87 : The parameter is incorrect.


Option Explicit

Private Declare PtrSafe Function FreeConsole Lib "kernel32" () As Long
Private Declare PtrSafe Function AllocConsole Lib "kernel32" () As Long
'https://learn.microsoft.com/en-us/windows/console/allocconsole

Sub Example()
    Dim l As Long
    
    l = FreeConsole
    Debug.Print "FreeConsole: " & l     ' 1
    
    If FreeConsole = 0 Then
        Debug.Print Err.LastDllError, "FreeConsole failed"
        Exit Sub
    End If
    
    l = AllocConsole
    Debug.Print "AllocConsole: " & l     ' 0
    
    If l = 0 Then
        Debug.Print Err.LastDllError ' 87 : The parameter is incorrect.
        Exit Sub
    End If
    
End Sub

Output:

FreeConsole: 1
AllocConsole: 0
 87 

N.B. I'm using Excel 365 (Version 2207 Build 1547.20284) on Windows 10 (20H2).

  • 2
    Not sure what you want to achieve. Usually, you simply use Debug.Print to write something into the immediate window. Never heard that someone wants to use a console to debug VBA – FunThomas Oct 12 '22 at 12:24
  • The console is built into the editor, press Ctrl+G to bring it up. If you want to present it to the user, you need to make your own UI and `Debug.Print` wrapper – Mathieu Guindon Oct 12 '22 at 14:14
  • cmd.exe with parameters if you really want to display to this window see: [link]https://stackoverflow.com/questions/17956651/execute-a-command-in-command-prompt-using-excel-vba – Red Hare Oct 12 '22 at 14:26
  • Or you could write log information to a text-file? – Olle Sjögren Oct 12 '22 at 15:01
  • I already log to both text files and the immediate window, however, I have some data that needs text + colour. – William Bettridge-Radford Oct 12 '22 at 15:16

0 Answers0