首页 > 解决方案 > VBA 组合框值返回“”,但已填充并选中

问题描述

我在 Excel VBA 中的一个表单中有 2 个组合框。两者都正确命名 (pricingcostReport),并且都填充了打开的工作簿的总列表。两者都被正确预选,寻找其值中是否存在特定字符串。所以当我点击提交按钮时,我想检查每个组合框的值,发生的事情很奇怪。

根据每个函数 (UserForm_Initializebutton_Click) 的顺序,结果会有所不同。检查评论以查看详细信息。

Private Sub UserForm_Initialize()
    'populate each Combobox with the list of open Workbooks
    For Each book In Workbooks
        pricing.AddItem (book.Name)
        costReport.AddItem (book.Name)
    Next

    'preselect the Value of each, depending on the presence of a specific word
    'both Comboboxes end up correctly selected
    For Each book In Workbooks
        If InStr(1, book.Name, "pricing", 1) > 0 Then
            pricing.Value = book.Name
        End If
        If InStr(1, book.Name, "cost", 1) > 0 Then
            costReport.Value = book.Name
        End If
    Next
End Sub

Private Sub button_Click()
    Dim getPricing As String
    getPricing = "-" & Me.pricing.Value & "-"
    
    Dim getCostReport As String
    getCostReport = "-" & Me.costReport.Value & "-"
    
    Debug.Print getPricing
    Debug.Print getCostReport

    'if button_Click() is put before UserForm_Initialize()
    '   getPricing prints "-correct text-"
    '   getCostReport prints "--"

    'but if button_Click() is put after UserForm_Initialize()
    '   getPricing prints "--"
    '   getCostReport prints "-correct text-"
End Sub

最奇怪的是,如果我在执行表单时用鼠标光标手动选择其他值(或相同的值),那么两个值都会正确存储。因此,我认为这可能是一个听众或时间问题。我尝试将Initialize事件更改为Activate,并且我也尝试使用 Wait for a few seconds,但均无效。

你可以在这里看到一个代表

标签: excelvbacombobox

解决方案


推荐阅读