首页 > 解决方案 > 如果必填字段为空,则禁用命令按钮

问题描述

我正在用 excel-ActiveX 创建一个表单,但我不知道如何在所有必填字段(文本框和组合框)为空的情况下禁用命令按钮。我已附上示例表格供您参考。

样本洛杉矶表格

标签: excelvba

解决方案


使用*_Change每个控件的事件(以及可选的UserForm_Activate事件)来设置.Enabled控件按钮的属性。

例如,在具有 1 个 ComboBox ( ComboBox1)、2 个 TextBox (TextBox1TextBox2) 和 1 个 CommandButton ( CommandButton1) 的简单用户窗体上,以下代码将确保CommandButton1禁用它,除非其他 3 个控件中的每个控件中都有数据:

Option Explicit

Private Sub CheckMandatoryFields()
    'Is a separate sub to make it easy to edit for all Controls at the same time
    If Len(TextBox1.Value) > 0 And Len(TextBox2.Value) > 0 And Len(ComboBox1.Value) > 0 Then
        CommandButton1.Enabled = True
    Else
        CommandButton1.Enabled = False
    End If
End Sub

Private Sub CommandButton1_Click()
    MsgBox "Button is enabled!"
End Sub

Private Sub ComboBox1_Change()
    CheckMandatoryFields
End Sub

Private Sub TextBox1_Change()
    CheckMandatoryFields
End Sub

Private Sub TextBox2_Change()
    CheckMandatoryFields
End Sub

Private Sub UserForm_Activate()
    CheckMandatoryFields
End Sub

如果您的按钮和控件在工作表中,那么您需要更改UserForm_ActivateWorksheet_Activate. 如果它们在不同的工作表中,或者一些在工作表中,而另一些在用户窗体中,那么您将需要完全限定您的引用(例如Sheet1.Textbox1.Value

如果您在工作表中使用表单控件而不是 ActiveX 控件,则不能使用_Change事件,并且引用对象的方式不同:

Sheet1.Shapes("TextBox1").TextFrame2.TextRange.Text 'The value of TextBox1
Sheet1.Shapes("ComboBox1").ControlFormat.Value 'Which Number item in ComboBox1 is selected
Sheet1.Shapes("ComboBox1").ControlFormat.List(n) 'The value of the nth item in ComboBox1

表单控件按钮没有Enabled属性 - 但是,如果你有一个“什么都不做”宏,你可以像这样躲避它:

Sub DoNothing()
    'As it says
End Sub

Sub MakeASound()
    Beep
End Sub

Sub ToggleButton()
    If Sheet1.Shapes("Button 1").OnAction = "Sheet1!DoNothing" Then 'Disable Button 1
        Sheet1.Shapes("Button 1").OLEFormat.Object.Font.ColorIndex = 16 'Font colour = Grey
        Sheet1.Shapes("Button 1").OnAction = "Sheet1!DoNothing"
    Else 'Enable Button 1
        Sheet1.Shapes("Button 1").OLEFormat.Object.Font.ColorIndex = 1 'Font colour = Black
        Sheet1.Shapes("Button 1").OnAction = "Sheet1!MakeASound"
    End If
End Sub

推荐阅读