问题
I want to check if a userform is loaded or not while running a code. I tried several ways, no-one is working. I remember I did that before, but I can't recall my workaround. Any idea?
I found some solutions here and other places, they also was not working!
The issues are …
- vba.userforms just accepts index numbers, not string indexes,
- on a loop over the userforms some properties like name is not accessible to check!
Here are my Tries:
Public Function IsFormVisible(FrmName As String) As Boolean
On Error GoTo errorH
IsFormVisible = False
Set Frm = UserForms(FrmName)
If Not Frm Is Nothing Then IsFormVisible = True
End Function
errorH:
IsFormVisible = False
End Function
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As UserForm
On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If Frm.Name = FrmName Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
回答1:
Here are two simple options. First, you could declare frm
as Object
:
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As Object
On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If LCase$(Frm.Name) = LCase$(FrmName) Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
Or second, you could use TypeName
instead of .Name
:
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As UserForm
'On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If lcase$(TypeName(Frm)) = lcase$(FrmName) Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
I've made both of these case insensitive.
回答2:
I think the code for IsFormVisible
just misses one line of code if you really need to test for visibility.
HINT The question is as Rory pointed out rightfully about whether a userform is loaded or not. And for this question his answer is absolutely right.
Public Function IsFormVisibleA(FrmName As String) As Boolean
Dim Frm As Object
On Error GoTo errorH
IsFormVisibleA = False
For Each Frm In VBA.UserForms
If LCase$(Frm.Name) = LCase$(FrmName) Then
If Frm.Visible Then
IsFormVisibleA = True
Exit Function
End If
End If
Next
errorH:
IsFormVisibleA = False
End Function
You can test it like that. If you only load the form without showing it the function IsFormVisible will return true although the form is not visible.
Sub Testfrm()
Dim Frm As frmMy
Set Frm = New frmMy
' Frm.Show vbModeless
Debug.Print Frm.Name
Debug.Print IsFormVisibleA("frmMy"), IsFormVisible("frmMy")
End Sub
来源:https://stackoverflow.com/questions/52818343/vba-check-if-a-particular-userform-is-loaded-or-not