您正在展示有限的预定义向用户提供一系列选项。
然而,你让他们毫不夸张地输入什么,没有验证,并与它一起滚动。
一个更好的替代方案将是沟InputBox
方法和与实际UserForm
向用户呈现,以使用户的输入约束到一个有限的,预先确定的设定的选择 - ComboBox
控制想到:
用户窗体的代码隐藏是非常简单的 - 隐藏在单击按钮时的形式,把“X-出”为取消,暴露用户的Selection
和形式是否是通过Property Get
取消会员,和填充的可能值下拉列表,从挑选:
Option Explicit
Private isCancelled As Boolean
Public Property Get Cancelled() As Boolean
Cancelled = isCancelled
End Property
Public Property Get Selection() As String
Selection = ComboBox1.Value
End Property
Private Sub CancelButton_Click()
isCancelled = True
Hide
End Sub
Private Sub OkButton_Click()
Hide
End Sub
Private Sub UserForm_Activate()
With ComboBox1
.Clear
.AddItem "Lorem"
.AddItem "Ipsum"
'...
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
isCancelled = True
Hide
End If
End Sub
现在你可以这样做:
Public Sub Test()
With New UserForm1
.Show
If Not .Cancelled Then
MsgBox .Selection
End If
End With
End Sub
此处理用户抵消提示,如果你的ComboBox
控制的Style
属性设置为fmStyleDropDownList
,那么用户绝对没有办法提供您不期望的值。您可以通过提供Property Get
和Property Let
成员来根据需要配置Title
和Instructions
标签,或者让调用代码负责提供有效值列表以填充ComboBox
。
这就是其中一个部分问题。下一部分是用另一个字符串值“映射”输入。这样做的最好的数据结构是Dictionary
,但键入Collection
可以很好的工作:
Dim values As Collection
Set values = New Collection
values.Add "string 1", "Lorem"
values.Add "string 2", "Ipsum"
'...
With New UserForm1
.Show
If Not .Cancelled Then
MsgBox values(.Selection)
End If
End With
当然有很多方式来填充你所需要的数据,既为组合框值和映射的集合中的字符串;你可以像这样对它们进行硬编码,或者从工作表上的Range
或者从数据库中获取它们,不管你的船是什么。
糟糕,框架标题中的拼写错误。好吧。 –
表单中的语言是什么?绝对是正确的方法顺便说一句。 –
@ASH [* Lorem Ipsum *来自Cicero于公元前45年写成的“de Finibus Bonorum et Malorum”(极端恶魔)的第1.10.32和1.10.33节。](http:// www。 lipsum.com/);-) –