Use VBA to Clear Immediate Window?

前端 未结 16 963
刺人心
刺人心 2021-01-30 00:19

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.

16条回答
  •  野的像风
    2021-01-30 00:33

    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
    

提交回复
热议问题