Search code examples
vbawindowsshellcommandsettings

I want to open Windows Settings screen via VBA code


  1. Press Windows+R in order to open Run Dialog Box.
  2. Type ms-settings: into Run Dialog Box.
  3. Press OK in order to open Windows Settings Screen.

Do you know any VBA code which gives me same result like above actions?

I mean I just want to open Windows Settings screen via VBA code.

Please note that I am a Windows 10 user.


Solution

    • Use API ShellExecute to execute script Start-Process ms-settings:
    Option Explicit
    
    #If VBA7 Then
        Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
            ByVal hwnd As LongPtr, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) As LongPtr
    #Else
        Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
            ByVal hwnd As Long, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) As Long
    #End If
    
    Sub OpenSystemSettings()
        ShellExecute 0, "open", "ms-settings:", vbNullString, vbNullString, vbNormalFocus
    End Sub
    

    Update:

    Question: how to close Windows Settings screen via ShellExecute? Like pressing Alt+F4

    Option Explicit
    #If VBA7 Then
        Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" ( _
            ByVal lpClassName As String, _
            ByVal lpWindowName As String) As LongPtr
        Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" ( _
            ByVal hwnd As LongPtr, _
            ByVal wMsg As Long, _
            ByVal wParam As LongPtr, _
            lParam As Any) As LongPtr
    #Else
        Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
            ByVal lpClassName As String, _
            ByVal lpWindowName As String) As Long
        Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
            ByVal hwnd As Long, _
            ByVal wMsg As Long, _
            ByVal wParam As Long, _
            lParam As Any) As Long
    #End If
    Sub CloseSystemSettings()
        Dim hwnd As LongPtr
        Dim result As LongPtr
        Const WIN_TITLE = "Settings"  ' modify as needed for non-English release
        hwnd = FindWindow(vbNullString, WIN_TITLE)
        If hwnd = 0 Then
            MsgBox "Can't find window: " & WIN_TITLE
        Else
            result = SendMessage(hwnd, &H10, 0, ByVal 0&)
        End If
    End Sub