用户窗体初始化检查,然后关闭



我有一个用户表单。这个想法是检查"管理员"工作表的列(15(中是否有任何"True"值。如果至少有一个"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

我的用户表单上的所有内容都按预期工作,除了我无法使其自动关闭的事实。 即卸载我不起作用。

有什么建议吗?

您应该在显示UserForm之前检查您的标准。您可以在调用UserForm的任何位置将其添加为条件。无需打开表单,只需在事先检查时立即关闭它。

True的第一个实例中,UserForm将打开并退出子。如果循环完成(未找到True值(,则 sub 将继续执行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

请查看您的代码; 你已经把 卸载我是在退出之后

'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

相关内容

最新更新