excel - 用户表单列表框点击代码不会触发
问题描述
我使用工具菜单在 Excel 2016 中创建了一个带有两个列表框的用户表单。我双击它们以创建 subs 并插入代码以检查何时选择一个。
这是代码:
Private sub SaleType_Click ()
If SaleType.Value ="Core" then
'make sale label visible
QTDV.visible =true
' show core option btn
Core.Visible = true
End if
End sub
当我从工具箱创建一个 ListBox 时,这是可行的,但每隔一次运行表单时,saletype ListBox 的值为 null,这是一个问题,因为我有一个检查以确保 ListBox 不为空。代码如下:
If saletype = "" then
Dim msg as string Msg = " please select sale type"
Msgbox msg, and vbcritical
End if
如果 ListBox 显示值null
,它不会将其视为空并跳过检查,如果我尝试saletype = null
它仍然会跳过它。
我搜索了一下,似乎在工具箱上创建 ListBoxes 很奇怪,因为 Excel 不知道它是什么类型的控件。我选择在 VBA 中创建 ListBoxes。
Private sub userform_initialize()
Dim saletype as msforms.Listbox
Set saletype = me.Controls.Add("Forms.ListBox.1", "SaleType")
但是,当运行表单并选择 ListBox 上的任何选项时,SaleType_Click
子不会触发。
解决方案
如果要实现事件处理(如 SaleType_Click),则需要使用 WithEvents 关键字声明对象:
Dim WithEvents saletype as msforms.Listbox
如果未设置变量/属性,则其值不存在,因此您需要验证 NULL 而不是空字符串 ("") - IsNull 函数可以做到这一点(= NULL 不起作用,因为 = 仅适用带值):
If IsNull (saletype.Value) then
推荐阅读
- excel - 使用宏在 Outlook 中发送或接收邮件后在 Excel 中写入日志
- node.js - Mongo在尝试保存数组时返回[object Object]
- spring-web - Spring 的 URIComponentsBuilder 将端口号的冒号 (:) 转换为斜杠 (/)
- wordpress - Wordpress 核心文件已更改
- javascript - 如何显示标记周围的圆圈?
- python - 使用 Mac 为我的 Kivy 应用程序创建 Windows 的 exe 文件
- python-3.x - tf.nn.ctc_beam_search_decoder 返回的 Log_probabilities
- c-preprocessor - C 每隔一段时间更换一次宏
- algorithm - 给定 n 个点的直角三角形的数量
- google-chrome - 使用 ctrl + 滚动的 Chrome 最新 v68 缩放页面