Use VBA to Clear Immediate Window?
Asked Answered
E

21

83

Does anyone know how to clear the immediate window using VBA?

While I can always clear it myself manually, I am curious if there is a way to do this programmatically.

Epifaniaepifano answered 18/4, 2012 at 5:30 Comment(0)
M
41

Below is a solution from here

Sub stance()
Dim x As Long

For x = 1 To 10    
    Debug.Print x
Next

Debug.Print Now
Application.SendKeys "^g ^a {DEL}"    
End Sub
Mebane answered 20/6, 2012 at 11:52 Comment(9)
I'm not very fond of VBA so I prefer shorter solutions. :) I'm glad this helps you although question was posted few months ago. :)Mebane
Odd. It looks simple enough. But when I run this from Access 2007, it's turning my NumLock off. Anyone know why?Infantile
The only problem with the code is that you can re-print to the immediate window after execution. Nothing will showFiling
Only problem with this solution is that Application.SendKeys seems to be very unpredictable. For instance, when using this in a different subprocedure, the initialization of my Userform will be effected (as weird as that sounds). While this is shorter, it sounds a little risky.Morpheme
For those wondering, the shortcut keys are Ctrl+G (to activate the Immediate window), then Ctrl+A (to select everything), then Del (to clear it).Mcconaghy
There is no SendKeys method in Application in MS Access 2016. You should run simply SendKeys ...Ulaulah
I discourage to use this method. VBE is a weird thingy and sometimes it tries to clear the code (or something else) instead of the Immediate.Ulaulah
Try using something like If Application.VBE.ActiveWindow.Caption = "Immediate" And Application.VBE.ActiveWindow.Visible Then Application.SendKeys "^a {DEL} {HOME}"to reduce unpredictability.Hiccup
@AustinD - However, as per this article, + seems to belong to Ctrl and ^ corresponds to Shift. So, .SendKeys and .OnKeys map keycodes differently?Roy
C
26

or even more simple

Sub clearDebugConsole()
    For i = 0 To 100
        Debug.Print ""
    Next i
End Sub
Chatelain answered 16/6, 2014 at 9:46 Comment(2)
I understand the other solutions are a lot more thorough, but I'm not sure why you were downvoted. This is the solution that worked for me - I just literally needed to clear it out, and putting a few blanks in worked great. Thanks!Hicks
Dirty but Funny way at least :-)Pilate
M
25

SendKeys is straight, but you may dislike it (e.g. it opens the Immediate window if it was closed, and moves the focus).

The WinAPI + VBE way is really elaborate, but you may wish not to grant VBA access to VBE (might even be your company group policy not to).

Instead of clearing you can flush its content (or part of it...) away with blanks:

Debug.Print String(65535, vbCr)

Unfortunately, this only works if the caret position is at the end of the Immediate window (string is inserted, not appended). If you only post content via Debug.Print and don't use the window interactively, this will do the job. If you actively use the window and occasionally navigate to within the content, this does not help a lot.

Mechellemechlin answered 23/11, 2012 at 7:50 Comment(4)
why would you dislike sendkeys?Humic
In theory, things can happen at the user interface between selecting the window and posting keys to it. So the message may deliver somewhere else. More realistic, you don't get errors if you targeted at a different application or version and the keys can do something completely different. Of course, as shorthand it's OK (instead of you pressing Ctrl-g Ctrl-a Del, why could VBA not do it?), but I would not deploy something to users with SendKeys if I can avoid it.Mechellemechlin
Just for the record: SENDKeys changes keyboard settings such as NUMLOCK for example... its annoying to say the leastViscounty
This happened to me - the ctrl+a delete wound up going to a code module window somehow and wiped out my code, which I didn't realize until it was too late to restore it. I don't recommend the SendKeys approach at all.Chinua
E
23

Much harder to do that I'd envisaged. I found an version here by keepitcool that avoids the dreaded Sendkeys

Run this from a regular module.

Updated as initial post missed the Private Function Declarations - poor copy and paste job by yours truly

Private Declare Function GetWindow _
Lib "user32" ( _
ByVal hWnd As Long, _
ByVal wCmd As Long) As Long
Private Declare Function FindWindow _
Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx _
Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long
Private Declare Function GetKeyboardState _
Lib "user32" (pbKeyState As Byte) As Long
Private Declare Function SetKeyboardState _
Lib "user32" (lppbKeyState As Byte) As Long
Private Declare Function PostMessage _
Lib "user32" Alias "PostMessageA" ( _
ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long _
) As Long


Private Const WM_KEYDOWN As Long = &H100
Private Const KEYSTATE_KEYDOWN As Long = &H80


Private savState(0 To 255) As Byte


Sub ClearImmediateWindow()
'Adapted  by   keepITcool
'Original from Jamie Collins fka "OneDayWhen"
'http://www.dicks-blog.com/excel/2004/06/clear_the_immed.html


Dim hPane As Long
Dim tmpState(0 To 255) As Byte


hPane = GetImmHandle
If hPane = 0 Then MsgBox "Immediate Window not found."
If hPane < 1 Then Exit Sub


'Save the keyboardstate
GetKeyboardState savState(0)


'Sink the CTRL (note we work with the empty tmpState)
tmpState(vbKeyControl) = KEYSTATE_KEYDOWN
SetKeyboardState tmpState(0)
'Send CTRL+End
PostMessage hPane, WM_KEYDOWN, vbKeyEnd, 0&
'Sink the SHIFT
tmpState(vbKeyShift) = KEYSTATE_KEYDOWN
SetKeyboardState tmpState(0)
'Send CTRLSHIFT+Home and CTRLSHIFT+BackSpace
PostMessage hPane, WM_KEYDOWN, vbKeyHome, 0&
PostMessage hPane, WM_KEYDOWN, vbKeyBack, 0&


'Schedule cleanup code to run
Application.OnTime Now + TimeSerial(0, 0, 0), "DoCleanUp"


End Sub


Sub DoCleanUp()
' Restore keyboard state
SetKeyboardState savState(0)
End Sub


Function GetImmHandle() As Long
'This function finds the Immediate Pane and returns a handle.
'Docked or MDI, Desked or Floating, Visible or Hidden


Dim oWnd As Object, bDock As Boolean, bShow As Boolean
Dim sMain$, sDock$, sPane$
Dim lMain&, lDock&, lPane&


On Error Resume Next
sMain = Application.VBE.MainWindow.Caption
If Err <> 0 Then
MsgBox "No Access to Visual Basic Project"
GetImmHandle = -1
Exit Function
' Excel2003: Registry Editor (Regedit.exe)
'    HKLM\SOFTWARE\Microsoft\Office\11.0\Excel\Security
'    Change or add a DWORD called 'AccessVBOM', set to 1
' Excel2002: Tools/Macro/Security
'    Tab 'Trusted Sources', Check 'Trust access..'
End If


For Each oWnd In Application.VBE.Windows
If oWnd.Type = 5 Then
bShow = oWnd.Visible
sPane = oWnd.Caption
If Not oWnd.LinkedWindowFrame Is Nothing Then
bDock = True
sDock = oWnd.LinkedWindowFrame.Caption
End If
Exit For
End If
Next
lMain = FindWindow("wndclass_desked_gsk", sMain)
If bDock Then
'Docked within the VBE
lPane = FindWindowEx(lMain, 0&, "VbaWindow", sPane)
If lPane = 0 Then
'Floating Pane.. which MAY have it's own frame
lDock = FindWindow("VbFloatingPalette", vbNullString)
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
While lDock > 0 And lPane = 0
lDock = GetWindow(lDock, 2) 'GW_HWNDNEXT = 2
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
Wend
End If
ElseIf bShow Then
lDock = FindWindowEx(lMain, 0&, "MDIClient", _
vbNullString)
lDock = FindWindowEx(lDock, 0&, "DockingView", _
vbNullString)
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
Else
lPane = FindWindowEx(lMain, 0&, "VbaWindow", sPane)
End If


GetImmHandle = lPane


End Function
Eunaeunice answered 18/4, 2012 at 5:43 Comment(7)
Thanks~~ It's much harder than I expected though :DEpifaniaepifano
nice idea +1, but the declaration of the Function GetWindow and GetKeyboardState is missing -1 :)Dalury
Doesn't work when used from code as expected since the clearing commands are queued and only happen after the calling code finishes.Agiotage
Blast from the past: this is code I wrote a decade or more ago!Trackandfield
@Trackandfield you are KeepitCool? :). The other day I answered a question here on multiple goal seek code - that I wrote a decade ago on aother forum. Getting older quickly :)Eunaeunice
It's [annoyingly] always the smallest coding things I'm trying to do that end up taking me the longest & frustrating me most -- Like searching Repeatedly, for Years, for This Exact Answer.......and you're gonna tell me it's been sitting right here for six years??  *sigh*Hube
Had to go to the Trust Center and enable the checkbox: Trust access to the VBA project object model. If you all don't see me again, it's because some malicious code took over my PC and I threw it off a cliff. But nice solution xDAddison
C
7

Here is a combination of ideas (tested with excel vba 2007) :

' * (this can replace your day to day calling to debug)

Public Sub MyDebug(sPrintStr As String, Optional bClear As Boolean = False)
   If bClear = True Then
      Application.SendKeys "^g^{END}", True

      DoEvents '  !!! DoEvents is VERY IMPORTANT here !!!

      Debug.Print String(30, vbCrLf)
   End If

   Debug.Print sPrintStr
End Sub

I do not like deleting the Immediate content (fear of deleting the code by accident, so the above is a hack on some of the code you all wrote.

This handles the problem Akos Groller writes about above: "Unfortunately, this only works if the caret position is at the end of the Immediate window"

The code opens the Immediate window (or puts the focus on it), sends a CTRL+END, followed by a flood of newlines, so the previous debug content is not in sight.

Please note, that DoEvents is crucial, otherwise the logic would fail (the caret position would not move in time to the end of the Immediate window).

Coffelt answered 7/2, 2015 at 5:47 Comment(0)
S
7

Marked answer does not work if triggered via button in worksheet. It opens Go To excel dialog box as CTRL+G is shortcut for. You have to SetFocus on Immediate Window before. You may need also DoEvent if you want to Debug.Print right after clearing.

Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^g ^a {DEL}"
DoEvents

For completeness, as @Austin D noticed:

For those wondering, the shortcut keys are Ctrl+G (to activate the Immediate window), then Ctrl+A (to select everything), then Del (to clear it).

Shively answered 12/4, 2018 at 11:42 Comment(3)
Yeah don't try to F8 step through this code... assuming you are running it within a module, the Immediate window will not SetFocus and all you will do is delete all code in your module window. Gotta just trust it works and call it without stepping.Hiccup
Try changing the second line to If Application.VBE.ActiveWindow.Caption = "Immediate" Then Application.SendKeys "^a {DEL} {HOME}"Hiccup
Or better yet... Application.VBE.ActiveWindow.Caption = "Immediate" And Application.VBE.ActiveWindow.Visible Hiccup
C
4
  • No SendKeys?
  • No VBA Extensibility?
  • No 3rd Party Executables?
  • No problem!

A Windows API Solution

Option Explicit

Private Declare PtrSafe _
            Function FindWindowA Lib "user32" ( _
                            ByVal lpClassName As String, _
                            ByVal lpWindowName As String _
                            ) As LongPtr
Private Declare PtrSafe _
            Function FindWindowExA Lib "user32" ( _
                            ByVal hWnd1 As LongPtr, _
                            ByVal hWnd2 As LongPtr, _
                            ByVal lpsz1 As String, _
                            ByVal lpsz2 As String _
                            ) As LongPtr
Private Declare PtrSafe _
            Function PostMessageA Lib "user32" ( _
                            ByVal hwnd As LongPtr, _
                            ByVal wMsg As Long, _
                            ByVal wParam As LongPtr, _
                            ByVal lParam As LongPtr _
                            ) As Long
Private Declare PtrSafe _
            Sub keybd_event Lib "user32" ( _
                            ByVal bVk As Byte, _
                            ByVal bScan As Byte, _
                            ByVal dwFlags As Long, _
                            ByVal dwExtraInfo As LongPtr)

Private Const WM_ACTIVATE As Long = &H6
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_CONTROL = &H11

Sub ClearImmediateWindow()

    Dim hwndVBE As LongPtr
    Dim hwndImmediate As LongPtr
    
    hwndVBE = FindWindowA("wndclass_desked_gsk", vbNullString)
    hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Immediate")
    PostMessageA hwndImmediate, WM_ACTIVATE, 1, 0&
    
    keybd_event VK_CONTROL, 0, 0, 0
    keybd_event vbKeyA, 0, 0, 0
    keybd_event vbKeyA, 0, KEYEVENTF_KEYUP, 0
    keybd_event VK_CONTROL, 0, KEYEVENTF_KEYUP, 0
    
    keybd_event vbKeyDelete, 0, 0, 0
    keybd_event vbKeyDelete, 0, KEYEVENTF_KEYUP, 0
    
End Sub
Chide answered 4/7, 2020 at 20:59 Comment(6)
ClearImmediateWindow called from a button click event works fine. When I call it before a lengthy operation, the contents of the immediate window are only selected, not deleted. DoEvents does not make any difference. Any idea why the delete key does not work in that particular case?Questionary
@Questionary The immediatee window might be losing focus before the keypress event is processed. If so, then adding DoEvents before a keypress will be ineffective; try adding it as the last line in the Sub. If that doesn't help then i would try replacing it with a small delay of 10ms (as the last line)Chide
Neither of the two options work and the the immediate window still has the focus when the procedure (open excel and read cells from a worksheet) is finished.Questionary
@Questionary I do not why your code fails, but I may be able to figure it out if you create a new question with a minimal reproduceable example and post a link to it in these comments.Chide
Wouldn't it be enough to implement the Active-Call and do the rest with SendKeys.Poole
Just to suggest before calling ClearImmediateWindow() check if VBA editor is opened with: If Application.VBE.MainWindow.Visible Then Call ClearImmediateWindow Theomancy
Q
4

Thanks ProfoundlyOblivious,

No SendKeys, check
No VBA Extensibility, check
No 3rd Party Executables, check
One minor problem:

Localised Office versions use another caption for the immediate window. In Dutch it is named "Direct".
I have added one line to get the localised caption in case FindWindowExA fails. For those who use both the English and Dutch version of MS-Office.

+1 for you for doing most of the work!

Option Explicit

Private Declare PtrSafe Function FindWindowA Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function FindWindowExA Lib "user32" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
Private Declare PtrSafe Function PostMessageA Lib "user32" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As Long
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As LongPtr)

Private Const WM_ACTIVATE As Long = &H6
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_CONTROL = &H11

Public Sub ClearImmediateWindow()
    Dim hwndVBE As LongPtr
    Dim hwndImmediate As LongPtr
    
    hwndVBE = FindWindowA("wndclass_desked_gsk", vbNullString)
    hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Immediate") ' English caption
    If hwndImmediate = 0 Then hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Direct") ' Dutch caption
    PostMessageA hwndImmediate, WM_ACTIVATE, 1, 0&
    
    keybd_event VK_CONTROL, 0, 0, 0
    keybd_event vbKeyA, 0, 0, 0
    keybd_event vbKeyA, 0, KEYEVENTF_KEYUP, 0
    keybd_event VK_CONTROL, 0, KEYEVENTF_KEYUP, 0
   
    keybd_event vbKeyDelete, 0, 0, 0
    keybd_event vbKeyDelete, 0, KEYEVENTF_KEYUP, 0
End Sub
Questionary answered 25/10, 2020 at 14:8 Comment(0)
W
3

I had the same problem. Here is how I resolved the issue with help from the Microsoft link: https://msdn.microsoft.com/en-us/library/office/gg278655.aspx

Sub clearOutputWindow()
  Application.SendKeys "^g ^a"
  Application.SendKeys "^g ^x"
End Sub
Wistrup answered 2/5, 2017 at 21:15 Comment(0)
V
2

After some experimenting, I made some mods to mehow's code as follows:

  1. Trap errors (the original code is falling over due to not setting a reference to "VBE", which I also changed to myVBE for clarity)
  2. Set the Immediate window to visible (just in case!)
  3. Commented out the line to return the focus to the original window as it's this line that causes the code window contents to be deleted on machines where timing issues occur (I verified this with PowerPoint 2013 x32 on Win 7 x64). It seems the focus is switching back before SendKeys has completed, even with Wait set to True!
  4. Change the wait state on SendKeys as it doesn't seem to be adhered to on my test environment.

I also noted that the project must have trust for the VBA project object model enabled.

' DEPENDENCIES
' 1. Add reference:
' Tools > References > Microsoft Visual Basic for Applications Extensibility 5.3
' 2. Enable VBA project access:
' Backstage / Options / Trust Centre / Trust Center Settings / Trust access to the VBA project object model

Public Function ClearImmediateWindow()
  On Error GoTo ErrorHandler
  Dim myVBE As VBE
  Dim winImm As VBIDE.Window
  Dim winActive As VBIDE.Window

  Set myVBE = Application.VBE
  Set winActive = myVBE.ActiveWindow
  Set winImm = myVBE.Windows("Immediate")

  ' Make sure the Immediate window is visible
  winImm.Visible = True

  ' Switch the focus to the Immediate window
  winImm.SetFocus

  ' Send the key sequence to select the window contents and delete it:
  ' Ctrl+Home to move cursor to the top then Ctrl+Shift+End to move while
  ' selecting to the end then Delete
  SendKeys "^{Home}", False
  SendKeys "^+{End}", False
  SendKeys "{Del}", False

  ' Return the focus to the user's original window
  ' (comment out next line if your code disappears instead!)
  'winActive.SetFocus

  ' Release object variables memory
  Set myVBE = Nothing
  Set winImm = Nothing
  Set winActive = Nothing

  ' Avoid the error handler and exit this procedure
  Exit Function

ErrorHandler:
   MsgBox "Error " & Err.Number & vbCrLf & vbCrLf & Err.Description, _
      vbCritical + vbOKOnly, "There was an unexpected error."
  Resume Next
End Function
Vermouth answered 3/3, 2014 at 21:11 Comment(1)
A word of caution when using Microsoft Visual Basic for Applications Extensibility (VBE): some malware recognition systems will flag it as malware. The reason being it can be used for malicious purposes, for instance to spread malware through DOC, XLS, and any file type that uses VBA. I recently tried to send an XLS file with VBE in it, and GMAIL flagged it as malware and wouldn't let me send it. So I put it in a password-protected ZIP file, and found those aren't allowed either. But I should add McAffee and Kaspersky is ok with it, I've used both and they do not flag my XLS files with VBE.Vibraphone
O
1

For cleaning Immediate window I use (VBA Excel 2016) next function:

Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub

But direct call of ClrImmediate() like this:

Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents    
    Debug.Print "next..."
End Sub

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames() - NOT before Debug.Print. Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).

Oshea answered 4/12, 2017 at 22:44 Comment(2)
Wow, 'Application.OnTime' is very powerful. I didn't know VBA could accept higher order functions!Medarda
The line with "next..." winds up being in the Immediate window after execution ends (unless this is the point of "next...", to suggest "carrying on" is what's "next"). Of course, commenting out the line with "next..." delivers a cleared Immediate window. And so does putting ClrImmediate AFTER the line with "next...". I would also put .SetFocus at end of "With" line and lose the word "With" and the line "End With".Gullah
L
1

All of the solutions posted above have problems when the ClearImmediate function is called from a higher level Subroutine. For instance the following will usually end up with an EMPTY immediate window !

sub HigherLevel
   debug.print "this message should disappear in 1 second"
   call AnyOfAboveSolutions
   debug.print "This message should appear in the immediate window"
End sub

But after many years I finally found a solution that works. First install the following to your VBA project.

    Option Explicit
Const Source = "c:\users\rdbmdl\"
Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub cls() ' also known as ClearScreen and ClearImmediateWindow
' see https://www.experts-exchange.com/questions/29228246/Vba-subroutines-to-clear-the-IDE-immediate-window-do-not-always-work.html

  ' the Cls routine Clears the immediate window during debugging.
  ' To install it you must create c:\users\rdbmdl\Vbaf5.vbs.
  ' if invoked from a runtime environment  ClearScreen will become disabled.

Dim safe As Single, ap As Object
Static Initialized As Boolean, Disabled As Boolean
    If Not Initialized Then
        Initialized = True
        If Dir(Source & "vbaf5.vbs") = "" Then
            MsgBox "Please install VbaF5.vbs"
            Disabled = True
        End If
    End If
    If Disabled Then Exit Sub
    safe = VBA.DateTime.Timer
    Shell Replace("wscript c:\users\rdbMdl\vbaf5.vbs ""%1""", "%1", GetCurrentProcessId), 1
Stop ' in a runtime environment Stop is ignored and ClearScreen gets disabled
      ' the Stop CANNOT be replaced with a Sleep. Things get very weird vba code that calls Cls gets a few bytes deleted.
    If VBA.DateTime.Timer - safe < 0.01 Then
       Disabled = True
    End If
End Sub

Then install the following to C:\users\rdbmdl\vbaF5.vbs

' see https://www.experts-exchange.com/questions/29228246/Vba-subroutines-to-clear-the-IDE-immediate-window-do-not-always-work.html
Dim objServices, objProcessSet, process, desired
    desired = "^g^a {DEL} {HOME}"
    desired = desired & "{F7}^+{F2}{RIGHT}+{RIGHT}"
    desired = desired & "{F5}"

    Set objShell = wscript.CreateObject("WScript.Shell")
    Set objargsinall = wscript.Arguments'
    Set objServices = GetObject("winmgmts:\\.\root\CIMV2")
    Set objProcessSet = objServices.ExecQuery("SELECT ProcessID FROM Win32_Process WHERE ProcessID =" & objargsinall(0), , 48)
   
    For Each process In objProcessSet
    objShell.AppActivate (process.ProcessID)
    objShell.SendKeys desired   
    Next
' see https://www.experts-exchange.com/questions/29228246/Vba-subroutines-to-clear-the-IDE-immediate-window-do-not-always-work.html
Landowner answered 17/11, 2021 at 12:47 Comment(0)
L
1

My 11/17/2021 answer used vbscript and was fairly complicated.
The following is MUCH simpler and is entirely VBA. 95% of the time ClearStop is the best solution, but ClearGo is useful if you are using debug.print to help measure resource consumption in long running programs.

Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Sub ClearStop()
    Application.SendKeys "^g^a^{DEL}"
    Stop
End Sub
Sub ClearGo()
    Application.SendKeys "^g^a^{DEL}" & IIf(GetKeyState(&H10) < 0, "", "{F5}")   'Shift key: see https://www.experts-exchange.com/questions/29228246/Vba-subroutines-to-clear-the-IDE-immediate-window-do-not-always-work.html
    Stop
End Sub
Landowner answered 28/11, 2021 at 23:48 Comment(0)
I
0

I'm in favor of not ever depending on the shortcut keys, as it may work in some languages but not all of them... Here's my humble contribution:

Public Sub CLEAR_IMMEDIATE_WINDOW()
'by Fernando Fernandes
'YouTube: Expresso Excel
'Language: Portuguese/Brazil
    Debug.Print VBA.String(200, vbNewLine)
End Sub
Irredentist answered 8/11, 2017 at 18:12 Comment(0)
P
0

Just checked in Excel 2016 and this piece of code worked for me:

Sub ImmediateClear()
   Application.VBE.Windows("Immediate").SetFocus
   Application.SendKeys "^{END} ^+{HOME}{DEL}"
End Sub
Pectin answered 8/10, 2019 at 19:15 Comment(3)
Worked for me, too, Excel 16, Win10.Gullah
But I'd still add If Application.VBE.ActiveWindow.Caption = "Immediate" Then _ before SendKeys, just in case.Gullah
This deleted all my code lolKeith
P
0

If you happen to be using Autohotkey here's the script I use.

The key command is Ctrl+Delete. It only works if the VBE is active.
When pressed it will clear the immediate window and then activate the code editor, via F7.

I tend to want to clear the immediate when while I'm coding so now I can just hit Ctrl-Delete and keep coding. 👍

#IfWinActive, ahk_class wndclass_desked_gsk

^Delete:: clearImmediateWindow()

#If

clearImmediateWindow() {
    Send, ^g
    Send, ^a
    Send, {Delete}
    Send, {F7}
}
Post answered 6/3, 2020 at 2:13 Comment(0)
O
0

Problems to solve:

  1. Clear the immediate window
  2. After clearing the immediate window, further Debug.Print statements don't work
  3. SendKeys sometimes Toggles NumLock (Microsoft Bug)
Option Explicit
Private Declare PtrSafe Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

Public Sub TestClearImmediateWindow()
    Dim x As Integer
    
    For x = 1 To 10
        Debug.Print String(20, Chr(64 + x))
    Next x
    ClearImmediateWindow
    Call Application.OnTime(DateAdd("s", 1, Now), "DoNextThing")
End Sub
Private Sub ClearImmediateWindow()
    Const NUMLOCKKEYCODE = 144
    Dim NumLockState As Integer
    
    NumLockState = GetKeyState(NUMLOCKKEYCODE)
    Call Application.SendKeys("^g^a{DEL}{F7}", True) ' Because of a bug, this line sometimes toggles NumLock
    If NumLockState <> GetKeyState(NUMLOCKKEYCODE) Then Call Application.SendKeys("{NUMLOCK}", True)
End Sub
Private Sub DoNextThing()
    Dim x As Integer
    
    For x = 1 To 10
        Debug.Print String(20, Chr(74 + x))
    Next x
End Sub
Owlet answered 5/7, 2022 at 20:19 Comment(0)
P
0
Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^a", True
Application.SendKeys "{DEL}", True

If error : Programmatic Access To Visual Basic Project Is Not Trusted

Parathion answered 6/12, 2022 at 13:31 Comment(1)
Pleast try to demonstrate your code with proper explaination. Thanks for participating in answers.Portfire
A
-1
Sub ClearImmediateWindow()
    SendKeys "^{g}", False
    DoEvents
    SendKeys "^{Home}", False
      SendKeys "^+{End}", False
      SendKeys "{Del}", False
        SendKeys "{F7}", False
End Sub
Axilla answered 15/9, 2016 at 2:25 Comment(3)
Hi Mike! Your answer clearly is worth a little more explanation. Kindly refer to stackoverflow.com/help/how-to-answer .Parkinson
Not good...this cleared all the code in my module! (Excel 2010)Scutari
Ctrl-Z restores! (Happened to me a dozen times while trying to execute some of the above code!!)Gullah
E
-1

I tested this code based on all the comments above. Seems to work flawlessly. Comments?

Sub ResetImmediate()  
        Debug.Print String(5, "*") & " Hi there mom. " & String(5, "*") & vbTab & "Smile"  
        Application.VBE.Windows("Immediate").SetFocus  
        Application.SendKeys "^g ^a {DEL} {HOME}"  
        DoEvents  
        Debug.Print "Bye Mom!"  
End Sub

Previously used the Debug.Print String(200, chr(10)) which takes advantage of the Buffer overflow limit of 200 lines. Didn't like this method much but it works.

Eustatius answered 5/10, 2018 at 11:47 Comment(0)
O
-1

I'm using this short code:

Sub clearDebug()
    SendKeys "^g^a{DEL}"
End Sub
Oxtail answered 20/1, 2022 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.