VBA Code Library

Move your window to the left screen and maximize it with VBA. Placing your window in a consistent position is a must before using mouse control macros. This is especially important if you’re using VBA to control your mouse and you have dual monitors.

This example maximizes a blank notepad window, but you can change the window you want to move by modifying the string in the AppActivate function.

A word of warning: The SendKeys method of VBA is quite unreliable, so use it with caution.


Maximize Window in Left Monitor

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
    Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
#End If
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Sub MaximizeWindow()
'DESCRIPTION: Move window to the left screen and maximize it to full screen
'DEVELOPER: Ryan Wells (wellsr.com)

'NOTE:  You can change AppActivate string to the name of your window if there's a particular window you want to maximize

On Error GoTo 101:
AppActivate "Untitled - Notepad"

SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "r", True
    Sleep 250
SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "m", True
    Sleep 250
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
        Sleep 250
    SetCursorPos 0, 0 'x and y position
        Sleep 250
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep 250
SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "x", True
Exit Sub
101:
MsgBox "Window not found", , "Window not found"
End Sub

Make powerful macros with our free VBA Developer Kit

This is actually pretty neat. If you have trouble understanding or remembering it, our free VBA Developer Kit can help. It’s loaded with VBA shortcuts to help you make your own macros like this one - we’ll send a copy, along with our Big Book of Excel VBA Macros, to your email address below.

I'll take a free VBA Developer Kit

That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below.