Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if userform open

I run a program which repeats itself. It should stop, when the user closes the userform. It runs without stopping.

Since the program calls itself every 8 seconds, I want to check at the end if the userform is still loaded / opened.

Public Sub NextPicture1()
   PictureChange = Now + TimeValue("00:00:08")
   If Onboarding_Projekt.Visible = True Then
      Application.OnTime PictureChange, "NextPicture1"
   End If
End Sub
like image 708
Lutscha Avatar asked May 28 '18 09:05

Lutscha


2 Answers

You can use a function like this:

Public Function IsLoaded(formName As String) As Boolean
Dim frm As Object
For Each frm In VBA.UserForms
    If frm.Name = formName Then
        IsLoaded = True
        Exit Function
    End If
Next frm
IsLoaded = False
End Function

Usage:

If IsLoaded("Form_Test") Then
    'Do Something
End If

Your code should look like this:

Public Sub NextPicture1()
   PictureChange = Now + TimeValue("00:00:08")
   If IsLoaded("Onboarding_Projekt") Then
      Application.OnTime PictureChange, "NextPicture1"
   End If
End Sub

Public Function IsLoaded(formName As String) As Boolean
    Dim frm As Object
    For Each frm In VBA.UserForms
        If frm.Name = formName Then
            IsLoaded = True
            Exit Function
        End If
    Next frm
    IsLoaded = False
End Function
like image 101
gizlmo Avatar answered Oct 06 '22 01:10

gizlmo


Here's a version that shows both whether it's loaded and whether it's visible:

Function Userform_Check( _
    form_name As String) _
        As Integer

    ' Returns:
    '   0 - Userform is not loaded
    '   1 - Loaded but not visible
    '   2 - Loaded and visible

    ' mUtilities.Userform_Check()

    Dim frm As Object

    Userform_Check = 0

    For Each frm In VBA.UserForms
        If frm.name = form_name Then
            Userform_Check = 1

            If frm.Visible Then Userform_Check = 2

            Exit For
        End If
    Next frm

' Function Userform_Check( _
    form_name As String) _
        As Integer
End Function
like image 32
RIck_R Avatar answered Oct 06 '22 01:10

RIck_R