仔细想了想该方法并没有所谓的防止查看和修改代码的作用,因为只要限制了宏功能或者不信任对VBA工程对象模型的访问就可以限制该功能从而打开VBE窗口。
禁止打开VBE窗口,可以防止查看和修改代码。
运行机理:在打开事件中添加windows监视,一旦VBE打开,就运行VBEwindow过程,并调用CheckVBE_Event过程强制关闭VBE
Thisworkbook模块代码
Private Sub Workbook_BeforeClose(Cancel As Boolean)
vbewin = False
End Sub
Private Sub Workbook_Open()
vbewin = True
VBEwindow
End Sub
Modul模块代码
Public Declare Function GetActiveWindow Lib "user32" () As Long
Public Declare Function GetClassName Lib "user32" Alias "GetClassNameA"_
(ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Public vbewin As Boolean
Sub VBEwindow()
Do While vbewin
DoEvents
Call CheckVBE_Event
Loop
End Sub
Sub CheckVBE_Event()
Dim hwnd As Long
Dim WText As String
Dim L As Long: L = 255
WText = String(255, " ")
hwnd = GetActiveWindow
L = GetClassName(hwnd, WText, L)
WText = Left(WText, L)
If WText = "wndclass_desked_gsk" Then
Application.VBE.CommandBars.FindControl(ID:=752).Execute
End If
End Sub