打开excel,找到开发工具 ,然后点击 Visual Basic进入代码编辑器窗口:
点击插入>>用户窗体,如下图所示:
如果此时运行,得到的效果如下所示,是没有最大化和最小化窗口的:
下面我们就来添加最大化最小化功能的实现。
双击窗体,进入代码编辑界面,输入以下代码:
Option Explicit Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Const GWL_STYLE = (-16) Private Const WS_THICKFRAME As Long = &H40000 '(恢复大小) Private Const WS_MINIMIZEBOX As Long = &H20000 '(最小化) Private Const WS_MAXIMIZEBOX As Long = &H10000 '(最大化) Private Sub UserForm_Initialize() Dim hWndForm As Long Dim IStyle As Long hWndForm = FindWindow("ThunderDFrame", Me.Caption) IStyle = GetWindowLong(hWndForm, GWL_STYLE) IStyle = IStyle Or WS_THICKFRAME '还原 IStyle = IStyle Or WS_MINIMIZEBOX '最小化 IStyle = IStyle Or WS_MAXIMIZEBOX '最大化 SetWindowLong hWndForm, GWL_STYLE, IStyle End Sub
将鼠标置于Sub
函数内部,按F5按键运行,得到如下效果:
这里需要说明的是,以上代码支持在64位操作系统运行,如果是32位系统,在导入库的时候,应使用下面一段代码:
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
与前面一段代码相比,发现唯一的区别在于,Declare
后面少了PtrSafe
,其原因是:Microsoft 提供了一个 Win32API.txt
文件,其中包含 1,500 个 Declare
语句以及一个用于剪切所需 Declare
语句并将其粘贴到您的代码中的工具。不过,这些语句适用于 32 位系统,必须使用下文讨论的信息将其转换为 64 位。现有 Declare
语句在 64 位 VBA 中不会进行编译,直到使用 PtrSafe
属性将它们标记为对 64 位安全。
具体可参阅MicroSoft Office 官方资料:32 位和 64 位版本的 Office 2010 之间的兼容性