问题是:如何加载组合框列表或为其赋予值,然后在我的工作表中调用它并从中获取选定的值?我有一个模块,我想调用我的 userform1 ,其中包含组合框它 。但是当我调试程序时,它只是组合框的显示。我认为它没有做任何事情...感谢您的时间..这是用户表单的代码:
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "weibull"
.AddItem "log-normal"
.AddItem "gambel"
.Style = fmStyleDropDownList
End With
End Sub
这就是我在子组件中要求显示组合框的方式:
UserForm1.Show
If ComboBox1.ListIndex = -1 Then
MsgBox "There is no item currently selected.", _
vbInformation, _
"Combo Box Demo"
Exit Sub
End If
MsgBox "You have selected " & ComboBox1.List(ComboBox1.ListIndex) & "." & vbNewLine _
& "It has " & ComboBox1.ItemData(ComboBox1.ListIndex) ", _
vbInformation, _
"Combo Box Demo"
第二部分是我在net中找到的,但它使程序至少显示组合框!
最佳答案
您正在尝试在用户窗体已关闭时访问控件。我说关闭是因为您没有使用 vbmodeless
来显示表单。因此,下一行可以运行的唯一方法是当表单关闭时。这是我的推荐。
在模块中声明公共(public)变量,该变量将在 useform 关闭时保存相关值,然后在以后使用它。例如
将此代码粘贴到用户表单中
Option Explicit
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "weibull"
.AddItem "log-normal"
.AddItem "gambel"
.Style = fmStyleDropDownList
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If ComboBox1.ListIndex <> -1 Then
SelectItem = ComboBox1.List(ComboBox1.ListIndex)
pos = ComboBox1.ListIndex + 1
End If
End Sub
并将其粘贴到模块中
Option Explicit
Public SelectItem As String, pos As Long
Sub Sample()
'
'~~> Rest of your code
'
SelectItem = "": pos = 0
UserForm1.Show
If pos = 0 Then
MsgBox "There is no item currently selected.", _
vbInformation, "Combo Box Demo"
Exit Sub
End If
MsgBox "You have selected " & SelectItem & "." & vbNewLine & _
"It is at position " & pos, vbInformation, "Combo Box Demo"
'
'~~> Rest of your code
'
End Sub
还有
组合框没有 .Itemdata
属性。它在 VB6 中可用,但在 VBA 中不可用。通过组合框的 .Itemdata
属性,我猜您正在尝试获取位置?
关于excel - 如何加载组合框,然后如何在vba中使用从中选择的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185096/