【发布时间】:2021-09-21 18:22:41
【问题描述】:
我正在构建一个将运行的宏,然后暂停宏并允许用户输入一个值,然后再次继续运行。我知道有可用的 InputBox 功能,但我希望该框弹出为下拉列表。我不知道如何做到这一点,任何帮助将不胜感激。
【问题讨论】:
-
创建一个用户表单并在其上放置一个组合框。使用此用户表单而不是 msgbox。
-
悉达多感谢您的回复!你介意给我看一个代码是什么样子的例子吗
我正在构建一个将运行的宏,然后暂停宏并允许用户输入一个值,然后再次继续运行。我知道有可用的 InputBox 功能,但我希望该框弹出为下拉列表。我不知道如何做到这一点,任何帮助将不胜感激。
【问题讨论】:
悉达多感谢您的回复!你介意给我看一个代码是什么样子的例子吗——钓鱼王 13 6 分钟前
希望这能让你走上正轨……
添加一个用户窗体并向其添加一个组合框。我在组合中添加了一些基本数据,以向您展示它是如何工作的。根据需要进行更改
你的用户表单会有类似这样的代码
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "option1"
.AddItem "option2"
.AddItem "option3"
.AddItem "option4"
.AddItem "option5"
End With
End Sub
Private Sub CommandButton1_Click()
If ComboBox1.Text <> "" Then MsgBox "the user chose or typed " & ComboBox1.Text
End Sub
接下来修改你的宏,让它看起来像这样
Sub Sample()
'
'~~> Do Some Stuff
'
UserForm1.Show
'
'~~> Continue doing Some Stuff
'
End Sub
来自 cmets 的跟进
还有一个问题,如果我的下拉菜单的值来自一个命名范围。我该如何定义? – 钓鱼王 13 3 分钟前
使用.List 代替.AddItem
Private Sub UserForm_Initialize()
ComboBox1.List = Application.Transpose(Range("MyNamedRange"))
End Sub
【讨论】:
我认为很多人会使用公共变量从用户表单中获取值,这是一种简单但不那么有效的方法(在我看来)。
我希望这个例子应该是更好的方法。
首先创建您的用户表单:(此处命名为“UF_Combobox”)
在用户窗体代码中,创建一个既显示/关闭用户窗体又返回值的函数,通过该函数返回调用子程序:
Option Explicit
Function Select_Value(ByVal Question As String, ByRef Values() As Variant, Optional ByVal Default_Index As Long = -1) As Long
Dim index As Long
'Fill the question
Textbox.Value = Question
'Fill the combobox with values
For index = LBound(Values, 1) To UBound(Values, 1)
Combobox.AddItem Values(index)
Next index
'Select the default value
Combobox.ListIndex = Default_Index
'Display the question (= the userform)
Me.Show '| Rest of function is suspended until "me.hide" is triggered
'Get the index value
Select_Value = Combobox.ListIndex
'Close
Unload Me
我使用设置为多行的文本框而不是标签,这在您有很长的问题的情况下会更好,它会将问题放在多行(如果需要,调整大小)而不是在边缘之后剪切它用户表单。
放置一个将触发“me.hide”函数的子程序,该函数将触发前一个函数的结束。命令按钮触发它。
Private Sub Button_Click()
Me.Hide
End Sub
以下是在通用模块中使用它的方法:
Option Explicit
Sub Choice()
'Variables
Dim days() As Variant
Dim chosen_day As String
Dim index As Long
'List
days = Array("monday", "tuesday", "wednesday", "thursday", "friday")
'Get the index value from the userform
index = UF_ComboBox.Select_Value(Question:="Meeting day ?", Values:=days, Default_Index:=0)
'Treatment
Select Case index
Case -1
chosen_day = "No day chosen !"
Case Else
chosen_day = days(index)
End Select
MsgBox chosen_day
End Sub
这只是一个简单的示例,但您显然可以根据需要添加选项和按钮。 “select_value”函数中的“必要”布尔参数可能是一个智能添加,因此您可以强制用户选择一个值。
【讨论】: