-->

Close all VBE windows (MS Access, VB for Aplicatio

2020-08-09 05:00发布

问题:

If you are like me and you work with lots of code you probably hate to close all open VBE code windows one by one. There is no functionality in VBE which would do it. How to do it?

回答1:

I was looking for a duplicate for this question. I couldn't fine one. So I ended up at Nee a code of API VBA to capture all handles of particular window by caption/Title and answering that as well :D

Well the logic is the same. Once you have the handle, simply close the window using SendMessage

Try this

Option Explicit

Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr

Private Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long

Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, lParam As LongPtr) As LongPtr

Const WM_SYSCOMMAND = &H112
Const SC_CLOSE = &HF060

Public Sub GetWindows()
    '~~> Pass Full Name or Partial Name. This is not case sensitive
    Debug.Print GetAllWindowHandles("Microsoft Visual Basic")
End Sub

Private Function GetAllWindowHandles(partialName As String)
    Dim hWnd As LongPtr, lngRet As Long
    Dim strText As String

    hWnd = FindWindowEx(0&, 0&, vbNullString, vbNullString)

    While hWnd <> 0
        strText = String$(100, Chr$(0))
        lngRet = GetWindowText(hWnd, strText, 100)

        If InStr(1, strText, partialName, vbTextCompare) > 0 Then
            '~~> Close the window
            SendMessage hWnd, WM_SYSCOMMAND, SC_CLOSE, 0
        End If

        '~~> Find next window
        hWnd = FindWindowEx(0&, hWnd, vbNullString, vbNullString)
    Wend
End Function

The above code absolutely works. Screenshot below. Opened 3 VBEs (One for MS Word. One for MS Powerpoint and One for MS Excel) and all three closed.