简体   繁体   English

从另一个表单 vba Excel 更新组合框

[英]Updating a combobox from another form vba Excel

I have a Userform1 form, inside which there is a combobox called categories, and this field is a list of options that I load into the combobox from a table in excel (using rowsource in the object properties).我有一个 Userform1 表单,其中有一个称为类别的组合框,该字段是我从 excel 中的表格加载到组合框的选项列表(在对象属性中使用 rowsource)。

From the opened Userform1, if I want to add a new option to the list that appears in the categories field, I put a button that opens a Userform2 where I can create categories.从打开的 Userform1 中,如果我想向类别字段中显示的列表添加一个新选项,我放置了一个按钮来打开 Userform2,我可以在其中创建类别。 But once I create it and close Userform2 the combobox of Userform1 is not updated.但是一旦我创建它并关闭 Userform2,Userform1 的组合框就不会更新。 How can I refresh it so that the new option I created from Userform 2 appears?如何刷新它以便出现我从 Userform 2 创建的新选项?

Thank you very much非常感谢

Set the rowsource at runtime in UserForm_Initialize()在运行时在UserForm_Initialize()设置行源

Code in Userform1 Userform1 中的代码

Option Explicit

Private Sub UserForm_Initialize()
    PopulateCombo
End Sub

Sub PopulateCombo()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lRow As Long
    
    '~~> Change this to the relevant sheet
    Set ws = Sheet1
    
    With ws
        '~~> Find Last Row in Col A
        '~~> Change column as applicable
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        '~~> Identify the range starting from A1
        '~~> Change as applicable
        Set rng = .Range("A1:A" & lRow)
        
        '~~> Set your rowsource
        ComboBox1.RowSource = rng.Address(, , , True)
    End With
End Sub

And then you can reset the RowSource using the PopulateCombo code from Userform2然后您可以使用Userform2PopulateCombo代码重置RowSource

Something like就像是

Code in Userform2 Userform2 中的代码

Private Sub CommandButton1_Click()
    '
    '~~> After adding data
    '
    
    UserForm1.PopulateCombo
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM