【问题标题】:How to store selections in comboboxes to variables in vba如何将组合框中的选择存储到vba中的变量
【发布时间】:2022-11-22 18:02:15
【问题描述】:

我有以下用户窗体:

用户从下拉列表中选择他们的姓名和年龄,这在 MyForm(Code)

Private Sub UserForm_Activate()
With Me.ComboBox2
    .Clear
    .AddItem "Joe"
    .AddItem "Jack"
    .AddItem "Dan"
 
End With

With Me.ComboBox3
    .Clear
    .AddItem "30"
    .AddItem "40"
    .AddItem "50"
End With
End Sub

此窗体从以下宏运行。要清楚,用户将有一个 activecell 然后运行宏,这是在 module1

Sub MainValues()
    MyForm.Show
    Dim Name As String
    Dim Age As String
   ' Debug.Print field
    Worksheets("Sheet1").Activate
    ActiveCell.Formula = "=concatenate(Name, Age)"
  
End Sub

我正在尝试从表单中的两个组合框中进行选择,然后连接这些值并将它们放在 activecell 中

【问题讨论】:

  • ActiveCell.Value = Name & " " & Age
  • 谢谢,但如何将两个框中的选择存储到变量 Name 和 Age 中?
  • 在要粘贴到单元格中的公式中,您使用引用“姓名”和“年龄”,但 XL 表中不存在这些,它们仅存在于 VBA 模块中。所以公式 ActiveCell.Formula = "=concatenate(Name, Age)" 会给你一个错误,因为 NameAge 都不作为工作表中的命名范围存在。所以上面@braX 的回答应该可以解决你的问题。
  • MainValues 方法在一个模块中,而两个组合框在一个表单中。您只能通过以组合框的值作为参数调用模块中的方法,将值从表单传输到模块方法吗?或者,将 MainValues 方法移动到表单并在 ComboBoxes 更改后调用它?
  • Name = Me.Combobox2.Value

标签: excel vba


【解决方案1】:

尝试这个:

Private Sub ComboBox2_Change()

    Call MainValuesInForm 'use this if you want to trigger after selection of the value

End Sub

Private Sub ComboBox3_Change()
    
    Call MainValuesInForm 'use this if you want to trigger after selection of the value

End Sub

Private Sub MainValuesInForm()
    
    Dim Name As String
    Dim Age As String
    
    Name = Me.ComboBox2.Value
    Age = Me.ComboBox3.Value
    
    ActiveCell.Value = Name & " " & Age
    
End Sub

Private Sub SubmitButton_Click()
    
    Call MainValuesInForm 'or use this if you want to trigger by means of the 'Submit' (or Insert) button
    
End Sub

Private Sub UserForm_Initialize()
    With Me.ComboBox2
        .Clear
        .AddItem "Joe"
        .AddItem "Jack"
        .AddItem "Dan"
     
    End With
    
    With Me.ComboBox3
        .Clear
        .AddItem "30"
        .AddItem "40"
        .AddItem "50"
    End With
End Sub

【讨论】:

  • 这几乎完全符合我的要求。有没有办法只在按下提交按钮时将连接写入单元格?
  • 是的,删除每个 ComboBoxes 的 Call MainValuesInForm...
猜你喜欢
  • 2019-12-16
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多