Function FormIsActive(sName AsString) AsBoolean Dim i AsInteger For i = 0To VBA.UserForms.Count - 1 FormIsActive = UserForms(i).Name = sName If FormIsActive ThenExitFunction Next i EndFunction
Sub LoadUserfrom() Userform1.Show EndSub
'测试: 运行LoadUserfrom前是否得到False,而运行LoadUserfrom后是否得到True的结果? Sub Test() MsgBox FormIsActive("UserForm1"), 64 EndSub
方法二(改进一)
Take a look at attached file and play with the three buttons.
Function FormIsActive(sName AsString) AsBoolean Dim i AsInteger For i = 0To UserForms.Count - 1 FormIsActive = UserForms(i).Name = sName If FormIsActive ThenExitFunction Next i EndFunction
Sub LoadUserform1() If FormIsActive("UserForm2") Then MsgBox "UserForm2 is active so we're unloading it NOW!" Unload UserForm2 EndIf UserForm1.Show EndSub
Sub LoadUserform2() UserForm2.Show EndSub
Sub Test() If FormIsActive("UserForm1") AndNot FormIsActive("UserForm2") Then MsgBox "UserForm1 is Active! UserForm2 is not!" ElseIf FormIsActive("UserForm2") AndNot 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!" EndIf EndSub