首页 > 解决方案 > 用户表单列表框点击代码不会触发

问题描述

我使用工具菜单在 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子不会触发。

标签: excelvba

解决方案


如果要实现事件处理(如 SaleType_Click),则需要使用 WithEvents 关键字声明对象:

Dim WithEvents saletype as msforms.Listbox

如果未设置变量/属性,则其值不存在,因此您需要验证 NULL 而不是空字符串 ("") - IsNull 函数可以做到这一点(= NULL 不起作用,因为 = 仅适用带值):

If IsNull (saletype.Value) then

推荐阅读