Ẩn TitleBar userform trong vba excel

 Cách ẩn TitleBar của Userform, nhiều khi bạn muốn ẩn Button close mặc định của userform để nhìn cho nó ngầu :) thì bài này cũng sẽ giúp bạn thực hiện được điều đó luôn.

Giờ bắt đầu thôi, đầu tiên bạn tạo một Module  có nội dung như sau:


Option Explicit
Option Private Module

Public Const GWL_STYLE = -16
Public Const WS_CAPTION = &HC00000
#If VBA7 Then
Public Declare PtrSafe Function GetWindowLong _
Lib "user32" Alias "GetWindowLongA" ( _
ByVal hWnd As LongPtr, _
ByVal nIndex As Long) As Long
Public Declare PtrSafe Function SetWindowLong _
Lib "user32" Alias "SetWindowLongA" ( _
ByVal hWnd As LongPtr, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Public Declare PtrSafe Function DrawMenuBar _
Lib "user32" ( _
ByVal hWnd As LongPtr) As Long
Public Declare PtrSafe Function FindWindowA _
Lib "user32" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As LongPtr
#Else
Public Declare Function GetWindowLong _
Lib "user32" Alias "GetWindowLongA" ( _
ByVal hWnd As Long, _
ByVal nIndex As Long) As Long
Public Declare Function SetWindowLong _
Lib "user32" Alias "SetWindowLongA" ( _
ByVal hWnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Public Declare Function DrawMenuBar _
Lib "user32" ( _
ByVal hWnd As Long) As Long
Public Declare Function FindWindowA _
Lib "user32" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
#End If

Sub HideTitleBar(frm As Object)
#If VBA7 Then
Dim lFrmHdl As LongPtr
#Else
Dim lFrmHdl As Long
#End If
Dim lngWindow As Long
lFrmHdl = FindWindowA(vbNullString, frm.Caption)
lngWindow = GetWindowLong(lFrmHdl, GWL_STYLE)
lngWindow = lngWindow And (Not WS_CAPTION)
Call SetWindowLong(lFrmHdl, GWL_STYLE, lngWindow)
Call DrawMenuBar(lFrmHdl)
End Sub

Sub ShowTitleBar(frm As Object)
#If VBA7 Then
Dim lFrmHdl As LongPtr
#Else
Dim lFrmHdl As Long
#End If
Dim lngWindow As Long
lFrmHdl = FindWindowA(vbNullString, frm.Caption)
lngWindow = GetWindowLong(lFrmHdl, GWL_STYLE)
lngWindow = lngWindow + (WS_CAPTION)
Call SetWindowLong(lFrmHdl, GWL_STYLE, lngWindow)
Call DrawMenuBar(lFrmHdl)
End Sub

sau đó trong userform bạn chỉ cần dùng đoạn code dưới đây để thực thi câu lệnh trong Module mà bạn vừa tạo ở trên:

Private Sub UserForm_Initialize()
HideTitleBar Me
End Sub
Chú ý:Trong Userform của bạn cần tạo một CommandButton để Close from có nội dung:

Private Sub CommandButton1_Click()
Unload Me
End Sub
Hehe giờ thì tận hưởng sự ngầu của bạn đi nào.

No comments :