需要使用组合框列表打开用户表单但已选择值

时间:2015-05-04 04:44:48

标签: excel excel-vba combobox userform vba

我有一个工作正常的用户表单。现在我需要编辑我使用userform选择的一些值,因此我想打开包含已选择值的userform。我已经有了用于保存某些工作表中的值的用户窗体,我尝试打开相同的用户窗体,但是当我打开用户窗体时,我已经选择了已选择的值。

我该怎么办?这是我的代码:

Private Sub CommandButton1_Click()

    Worksheets("Info").Activate

    With Worksheets("Info").Range("A:A")
        Set c = .Find(ComboBox1.Value, LookIn:=xlValues)
        If Not c Is Nothing Then

            Dim cliente As String
            Dim prov As String
            Dim dia As Integer
            Dim mes As String
            Dim año As Long
            Dim prod As String
            Dim fob As Long
            Dim hon As Variant
            Dim fee As Variant
            Dim cont As Integer
            Dim est As Integer
            cliente = c.Offset(0, 1).Value
           prov = c.Offset(0, 2).Value
           dia = c.Offset(0, 3).Value
           mes = c.Offset(0, 4).Value
           año = c.Offset(0, 5).Value
           prod = c.Offset(0, 6).Value
           fob = c.Offset(0, 7).Value
           hon = c.Offset(0, 8).Value
           fee = c.Offset(0, 9).Value
           cont = c.Offset(0, 10).Value
           est = c.Offset(0, 21).Value
           '
       End If
   End With
   'HERE STARTS THE PROBLEM!!!
   ' Now I open the userform, I need comboboxs open with the old values           
   UserForm1.Show
   UserForm1.ComboBox1.Value = cliente
   UserForm1.ComboBox1.Value = prov
   UserForm1.ComboBox1.Value = dia
   UserForm1.ComboBox1.Value = mes
   UserForm1.ComboBox1.Value = año
   UserForm1.TextBox1.Value = prod
   UserForm1.TextBox1.Value = fob
   UserForm1.TextBox1.Value = hon
   UserForm1.TextBox1.Value = fee
   UserForm1.TextBox1.Value = cont
   UserForm1.ComboBox1.Value = est

End Sub

2 个答案:

答案 0 :(得分:0)

使用以下语法向ComboBox添加项目:

ComboBox1.AddItem "your value"
像这样:

UserForm1.ComboBox1.AddItem = cliente

要显示默认项目,请使用其索引:

UserForm1.ComboBox1.ListIndex = 2

如果你只有它的文字使用循环:

For i = 1 To ComboBox1.ListCount
    If (ComboBox1.List(i) = myValue) Then
        ComboBox1.ListIndex = i
        Exit For
    End If
Next i

答案 1 :(得分:0)

UserForm1.Show默认为模态,因此您需要在显示表单之前设置其属性。代码当前所做的是显示表单,然后在表单退出后创建 new UserForm1(旧的已经卸载),设置其属性,然后允许它超出范围。试试这个:

Dim form_one As UserForm1

Set form_one = New UserForm1
temp.Controls("ComboBox1").Value = cliente
'etc...
form_one.Show

如果我正确理解了工作流程,那么在用户选择所有内容而不是卸载它之后,更简单的解决方案可能是.Hide