如何使用Excel VBA最大化特定监视器上的窗口?

时间:2017-02-22 07:52:07

标签: excel vba multiscreen

我想使用Excel VBA在特定屏幕上最大化窗口。

我使用了这段代码:

With ActiveWindow
    .WindowState = xlNormal
    .Left = 1200
    .WindowState = xlMaximized       
End With

如果监视器2右侧监视,则代码可以工作1.如果是相反的方法,则接近失败(然后我必须使用-1200)。

这个宏应该可以在不同的PC上运行,我不知道系统是如何配置的。是否有可能检测到连接了多少台显示器并直接寻址我想要最大化窗口的相应显示器?

2 个答案:

答案 0 :(得分:1)

如评论中所述,您需要使用Windows API;这是另一个(相对简单易用)API,它帮助我确定用户表单是否已移出屏幕的可见区域: GetSystemMetrics Lib" User32"

根据Office版本声明函数:

#If Win64 Then  'Win64=true, Win32=true, Win16= false
    Private Declare PtrSafe Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
    Private Declare PtrSafe Function apiGetSystemMetrics32 Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#ElseIf Win32 Then  'Win32=true, Win16=false
    Private Declare Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#Else   ' Win16=true
#End If

通用功能:

Public Function dllGetMonitors() As Long
    Const SM_CMONITORS = 80
    dllGetMonitors = apiGetSystemMetrics(SM_CMONITORS)
End Function


'The width of the virtual screen, in pixels.
'The virtual screen is the bounding rectangle of all display monitors

Public Function dllGetHorizontalResolution() As Long
    Const SM_CXVIRTUALSCREEN = 78
    dllGetHorizontalResolution = apiGetSystemMetrics(SM_CXVIRTUALSCREEN)
End Function

Public Function dllGetVerticalResolution() As Long
    Const SM_CYVIRTUALSCREEN = 79
    dllGetVerticalResolution = apiGetSystemMetrics(SM_CYVIRTUALSCREEN)
End Function

更多信息:http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx

我用来确定表单是否在屏幕外的功能:

Private Sub checkOffScreen(ByRef frm)
    Dim maxTop As Long, minLeft As Long, maxLeft As Long
    Dim defaultOffset As Byte, monitors As Byte

    monitors = celTotalMonitors.Value
    defaultOffset = 11
    minLeft = 0 - (frm.Width - defaultOffset)
    If monitors = 1 And celScreenResolutionX.Value > 1280 Then
        maxTop = 1180 - defaultOffset
        maxLeft = 1900 - defaultOffset
    Else
        maxTop = 750 - defaultOffset
        maxLeft = (960 * monitors) - defaultOffset
    End If
    With frm
        'If (celFormTop.Value < 0 Or celFormTop.Value > maxTop) Or _
            (celFormLeft.Value < minLeft Or celFormLeft.Value > maxLeft) Then
        'If .top < 0 Or .top > maxTop Or .Left < minLeft Or .Left > maxLeft Then
        If celFormTop.Value > maxTop Or celFormLeft.Value > maxLeft Then
            celFormTop = defaultOffset
            celFormLeft = defaultOffset
        End If
        If .Top > maxTop Or .left > maxLeft Then
            .Top = defaultOffset
            .left = defaultOffset
        End If
    End With
End Sub

答案 1 :(得分:0)

我不知道是否可以选择Application.Right,但我用-1200代替了1200,这对我来说很有效。

Application.WindowState = xlNormal
Application.Left = -1200
Application.WindowState = xlMaximized