excel - VBA 组合框值返回“”,但已填充并选中
问题描述
我在 Excel VBA 中的一个表单中有 2 个组合框。两者都正确命名 (pricing
和costReport
),并且都填充了打开的工作簿的总列表。两者都被正确预选,寻找其值中是否存在特定字符串。所以当我点击提交按钮时,我想检查每个组合框的值,发生的事情很奇怪。
根据每个函数 (UserForm_Initialize
和button_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,但均无效。
你可以在这里看到一个代表
解决方案
推荐阅读
- apache-spark - 使用 Apache Spark 时如何处理数据库的背压?
- python - 从 datetime64[ns] 到对象的熊猫(python)
- powershell - How to replace comma with new line
- visual-studio-code - 在 Visual Studio Code 中离线打开项目
- php - 具有多个 foreach 的访问角色不起作用
- ios - 按下按钮时防止解除 UIAlertController
- node.js - 如何读取节点 js api 上的发布数据
- sql - 查询公司和地区
- c++ - 根据启动时加载的参数动态切换
- javascript - 从机器人发送的随机报价 - 意外的识别器