首页 > Excel专区 > Excel函数 >

Excel VBA 窗体之添加最大最小化按钮 实现代码

Excel函数 2021-11-17 14:20:38

VBA的窗体和一般的程序窗体不太一样,一般的窗体都会有一个最大化和一个最小化按钮,而VBA窗体却只有一个关闭按钮。这样就使VBA的窗体在使用的时候会有一些不太方便,下面我们就来为它添加最大和最小化按钮。

Excel VBA 窗体之添加最大最小化按钮 实现代码

附件下载:

点击链接从百度网盘下载

操作如下:

◾在Excel的VBE窗口中插入一个用户窗体,将其命名为frmMaxMin。然后再添加一个模块。在窗体和模块中添加后面所列代码。

◾在工作薄中的任意工作表中添加一窗体按钮控件,将指定其设置宏为btnShowfrmMaxMin_Click。其供示范之用。

具体代码:

"ModToolsForm"模块代码

Sub btnShowfrmMaxMin_Click()
frmMaxMin.Show
End Sub

"frmTools" 窗体代码

'****************************************
'---此模块演示了给窗体添加最大最小化按钮---
'****************************************
Option Explicit
'以下声明API函数
#If Win64 Then '64位
Private Declare PtrSafe Function FindWindow _
Lib "user32" _
Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) _
As LongPtr
Private Declare PtrSafe Function GetWindowLong _
Lib "user32" _
Alias "GetWindowLongPtrA" ( _
ByVal hwnd As LongPtr, _
ByVal nIndex As Long) _
As LongPtr
Private Declare PtrSafe Function SetWindowLong _
Lib "user32" _
Alias "SetWindowLongPtrA" ( _
ByVal hwnd As LongPtr, _
ByVal nIndex As Long, _
ByVal dwNewLong As LongPtr) _
As LongPtr
Private Declare PtrSafe Function DrawMenuBar _
Lib "user32" ( _
ByVal hwnd As LongPtr) _
As Long
#Else '32位
'查找窗口
Private Declare Function FindWindow _
Lib "User32" _
Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) _
As Long
'取得窗口样式位
Private Declare Function GetWindowLong _
Lib "User32" _
Alias "GetWindowLongA" ( _
ByVal Hwnd As Long, _
ByVal nIndex As Long) _
As Long
'设置窗口样式位
Private Declare Function SetWindowLong _
Lib "User32" _
Alias "SetWindowLongA" ( _
ByVal Hwnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) _
As Long
'重绘窗体标题栏
Private Declare Function DrawMenuBar _
Lib "User32" ( _
ByVal Hwnd As Long) _
As Long
#End If
#If Win64 Then '64位
Private FHwnd As LongPtr
Private FIstype As LongPtr
#Else
Private FHwnd As Long
Private FIstype As Long
#End If
'以下定义常数
Private Const GWL_STYLE = (-16) '窗口样式
Private Const WS_MAXIMIZEBOX = &H10000 '最大化按钮
Private Const WS_MINIMIZEBOX = &H20000 '最小化按钮
'**************************************
'---------------主程序-----------------
'**************************************
Private Sub UserForm_Initialize()
'查找窗口句柄
FHwnd = FindWindow("ThunderDFrame", Me.Caption)
'取得窗口样式位
FIstype = GetWindowLong(FHwnd, GWL_STYLE)
'窗体样式位: 原样式和最大化、最小化按钮
FIstype = FIstype Or WS_MAXIMIZEBOX Or WS_MINIMIZEBOX
'重设窗体样式位
SetWindowLong FHwnd, GWL_STYLE, FIstype
'重绘窗体标题栏
DrawMenuBar FHwnd
End Sub


标签: excelVBA窗体添加最大最小化按钮实现

office教程网 Copyright © 2016-2020 https://www.office9.cn. Some Rights Reserved.