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's Kit
There's a lot to unpack here. To save time and become really good at VBA, make sure you get our free VBA Developer's Kit below. It's full of shortcuts, tips and pre-built macros to make writing VBA easier.

Sure, I'll take a free VBA Developer's Kit

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