用户表单初始化检查然后关闭

时间:2018-06-24 17:23:24

标签: excel vba excel-vba userform

我有一个用户表单。这个想法是要检查“管理”表中第(15)列中是否有任何“真”值。如果至少有一个“ True”值,则用户窗体将保持打开状态并继续其操作。

但是,如果找不到单个“ True”,则用户窗体将显示一条消息并自动关闭用户窗体。

Private Sub Userform_initialize()

    Dim LR As Long
    LR = Sheets("Project_Name").Cells(Rows.Count, "B").End(xlUp).Row

    With Worksheets("Admin")
        For i = 7 To LR
            If .Cells(i, 15) = "True" Then
                Exit For
            Else
                MsgBox ("No values found")
                Exit For
                Unload Me
            End If
        Next i
    End With
    ''' more code'''
End Sub

除了我无法使其自动关闭外,用户窗体上的所有内容均按预期工作。即卸载我不起作用。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

在显示UserForm之前,您应该检查条件。您可以在调用UserForm的任何位置将此添加为条件。您无需事先检查就可以立即将其关闭。

True的第一个实例上,UserForm将打开并退出子项。如果循环完成(未找到任何True值),则该子项将进入您的MsgBox

Sub OpenForm

With Worksheets("Admin")
    For i = 7 To LR
       If Cells(i,15) = "True" then 
         Userform.Show
         Exit Sub
       End If
    Next i
End With

MsgBox "No Values Found"

End Sub

答案 1 :(得分:1)

请查看您的代码;您已将“退出我”放在“退出”之后

    'Here is something for you to ponder on .........


    'Public enum type to add a set of particular vbKeys to the standard key set
    Public Enum typePressKeys
        vbNoKey = 0
        vbExitTrigger = -1
        vbAnswerKey = 100
        vbLaunchKey = 102
        vbPrevious = 104
        vbNext = 106
        vbSpecialAccessKey = 108
    End Enum

    Public Sub doSomethingWithMyUserform()
    Dim stopLoop As Boolean, testVal As Boolean, rngX As Range, LR As Long

    LR = ThisWorkbook.Sheets("Project_Name").Cells(Rows.Count, "B").End(xlUp).Row
    Set rngX = ThisWorkbook.Worksheets("Admin")
    testVal = False
    With rngX 'Your sub can do the check here
        For i = 7 To LR
           If .Cells(i, 15) = "True" Then
                testVal = True
                Exit For
            End If
        Next i
    End With

    If testVal Then
        Load UserForm1
        With UserForm1
            .Caption = "Something"
            .Tag = vbNoKey
            .button_OK.SetFocus 'Assuming you have a OK button on Userform1
        End With
        UserForm1.Show
        stopLoop = False
        Do
            If UserForm1.Tag = vbCancel Then
                'Do something perhaps
                Unload UserForm1
                stopLoop = True
            ElseIf UserForm1.Tag = vbOK Then
                'Do something specific
                Unload UserForm1
                stopLoop = True
            Else
                stopLoop = False
            End If
        Loop Until stopLoop = True
    else
       MsgBox "No values found"
    End If

    'Here you can close the way you want
    Set rngX = Nothing

    End Sub

        enter code here
相关问题