excel - 如何加载组合框,然后如何在vba中使用从中选择的值?

标签 excel combobox vba

问题是:如何加载组合框列表或为其赋予值,然后在我的工作表中调用它并从中获取选定的值?我有一个模块,我想调用我的 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/

相关文章:

excel - Excel VBA中的嵌套错误处理

vba - 逆向工程VBA代码Excel

excel - 计算列中空单元格中单元格的平均值

vba - 是否可以以编程方式取代 Excel 中的 native 超链接跟随行为?

excel - VBA剪切和粘贴错误

c# - 共享 ComboBox 数据源

excel - 嵌套 For 循环替代方案或优化

c# - 如何在 C# Windows 窗体中使用 linq 在组合框中显示多个字段?

java - 为什么我在 java 中的 JComboBox 的 ListCellRenderer 上出现类转换异常?

excel - 如何复制粘贴列调整带有图像的单元格的高度而不扭曲图像。 (Excel VBA)