使用userform上的按钮获取变量并继续使用sub

时间:2016-11-29 13:56:04

标签: excel vba excel-vba dictionary

我在excel中有一个userform,其中组合框使用另一个工作表的范围编译下拉列表。我已经使用范围中的字典定义了下拉列表,并强制组合框匹配(这样做是为了确保用户在添加新公司之前尝试查找公司)。但是,如果绝对需要,我希望他们能够将新公司添加到列表中,因此有一个标有“添加公司”的按钮,现在需要将他们输入的公司添加到列表/字典中,任何想法?< / p>

我想避免必须启动一个全新的用户窗体,最好我想到按钮的输入框on_click,但我不知道如何强制该变量重新回到原始用户窗体。

我目前的代码是:

Private Sub UserForm_Initialize()

    Dim Acctsht As Worksheet
    Dim ValSet
    Dim FinanInst
    Dim objFinanInst As Object
    Dim objAcctType As Object
    Dim objNickname As Object
    Dim objFourDig As Object
    Dim objAcctClass As Object
    Dim objDescript As Object
    Dim CompanyDict As New Scripting.Dictionary
    Dim Tempsht As Worksheet
    Dim NewCompTemp As String

    Set Acctsht = ActiveWorkbook.Sheets("Accounts")

    With Acctsht.Range("b2:b" & Range("b:b").SpecialCells(xlLastCell).Row)
        ValSet = .Value
    End With

    With CompanyDict
            .comparemode = 1
        For Each FinanInst In ValSet
            If Not .exists(FinanInst) Then .Add FinanInst, Nothing
        Next
        If .Count Then CBoxFinanInst.List = Application.Transpose(.keys)
    End With

    With CboxAcctType
        .AddItem "Checking Account"
        .AddItem "Fixed Loan"
        .AddItem "Investment Account"
        .AddItem "Money Market Account"
        .AddItem "Revolving Credit"
        .AddItem "Savings Account"

    End With

    With CBoxAcctClass
        .AddItem "Asset"
        .AddItem "Liability"

    End With

End Sub

Private Sub CButtonAddCompany_Click()

    Dim NewCompTemp As String

    Unload FrmCreateAccount

    NewCompTemp = InputBox("Please enter new company exactly as you wish it to appear", Title:="Create New Company")
    FrmCreateAccount.Show (NewCompTemp)

    Exit Sub

End Sub

在回应下面Jean-Pierre的评论时,我尝试了以下代码,但它仍然无效:

Private Sub CButtonAddCompany_Click()

Dim NewCompTemp As String
Dim Acctsht As Worksheet
Dim CompanyDict As New Scripting.Dictionary

Set Acctsht = ActiveWorkbook.Sheets("Accounts")

NewCompTemp = InputBox("Please enter new company exactly as you wish it to appear", Title:="Create New Company")

With Acctsht.Range("b2:b" & Range("b:b").SpecialCells(xlLastCell).Row)
    ValSet = .Value
End With

With CompanyDict
        .comparemode = 1
    For Each FinanInst In ValSet
        If Not .exists(FinanInst) Then .Add FinanInst, Nothing
    Next
    If .Count Then CBoxFinanInst.List = Application.Transpose(.keys)
End With

With CompanyDict
    .Add CompanyDict.Count + 1, NewCompTemp
End With

Exit Sub

End Sub

只有组合框中的原始下拉列表出现,无论输入什么内容并存储为NewCompTemp。

我明白了,感谢Jean-Pierre让我朝着正确的方向前进!我没有意识到我可以运行子程序并让它在表单上重置字典。

本质上,字典是从初始化操作设置的,但是,我没有意识到我可以在button_click操作上重新触发相同字典的设置。一旦我这样做并结束那个sub它就会返回到原来的userform sub并且瞧。感谢所有帮助,感谢您的耐心等待。 (这里的老生物学家学习新技能)。

0 个答案:

没有答案