其他思路:获得活动窗口句柄,进程外用GetForgroundWindow,进程内用GetActiveWindow

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function FormIsActive(sName As String) As Boolean
Dim i As Integer
For i = 0 To VBA.UserForms.Count - 1
FormIsActive = UserForms(i).Name = sName
If FormIsActive Then Exit Function
Next i
End Function

Sub LoadUserfrom()
Userform1.Show
End Sub

'测试: 运行LoadUserfrom前是否得到False,而运行LoadUserfrom后是否得到True的结果?
Sub Test()
MsgBox FormIsActive("UserForm1"), 64
End Sub

方法二(改进一)

Take a look at attached file and play with the three buttons.

Let me know if you still have question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

Option Explicit

Function FormIsActive(sName As String) As Boolean
Dim i As Integer
For i = 0 To UserForms.Count - 1
FormIsActive = UserForms(i).Name = sName
If FormIsActive Then Exit Function
Next i
End Function

Sub LoadUserform1()
If FormIsActive("UserForm2") Then
MsgBox "UserForm2 is active so we're unloading it NOW!"
Unload UserForm2
End If
UserForm1.Show
End Sub

Sub LoadUserform2()
UserForm2.Show
End Sub

Sub Test()
If FormIsActive("UserForm1") And Not FormIsActive("UserForm2") Then
MsgBox "UserForm1 is Active! UserForm2 is not!"
ElseIf FormIsActive("UserForm2") And Not FormIsActive("UserForm1") Then
MsgBox "UserForm2 is Active! UserForm1 is not!"
ElseIf FormIsActive("UserForm2") And FormIsActive("UserForm1") Then
MsgBox "UserForm1 and UserForm2 are both Active!"
Else
MsgBox "No active userform!"
End If
End Sub

UserForm.zip

最后方法

我现在用一个公共变量,就可以知道是否有窗体是活动


相关链接

  1. 【求助】怎样判断一个窗体是否在活动状态?

=================我是分割线=================

欢迎到公众号来唠嗑: