【问题标题】:Excel VBA, How to disable a commandbutton if one or more textbox is emptyExcel VBA,如果一个或多个文本框为空,如何禁用命令按钮
【发布时间】:2017-09-03 17:48:06
【问题描述】:

我用 1 个命令按钮和 4 个文本框制作了一个用户窗体,我想做的是:如果所有 4 个文本框仍然是空的,我想禁用命令按钮。

我已经找到仅适用于 1 个文本框的代码:

Private Sub TextBox1_Change()
    If TextBox1.Value = "" Then
        CommandButton1.Enabled = False
    Else
        CommandButton1.Enabled = True
    End If
End Sub

当我在 TextBox2 中使用相同的代码时,我被卡住了,CommandButton 已启用。当我使用代码(if TextBox1.value & TextBox2.value & TextBox3.value & TextBox4.value = "" then commandbutton1.enabled = false)时, 填充 TextBox1 后,CommandButton 仍处于启用状态。

【问题讨论】:

  • 如果所有框为空或任何框为空,您是否要禁用??
  • 如果所有框都是空的,我想禁用..

标签: excel vba


【解决方案1】:

您不需要任何 IF 条件。

CommandButton1.Enabled = cbool(Len(Textbox1.Text) + Len(Textbox2.Text) _
                          + Len(Textbox3.Text) + Len(Textbox4.Text))

CBool​​(x) = True 而 x 是 0 以外的任何数字,在这种情况下结果为 False。如果任何文本框有任何内容,它们的组合长度将大于 0,因此 CBool​​ 的结果为 True。

【讨论】:

  • 聪明的方法!
【解决方案2】:

用途:

If TextBox1.Value & TextBox2.Value & TextBox3.Value & TextBox4.Value = "" Then

如果值的串联为空,则所有值都必须为空。

【讨论】:

    【解决方案3】:

    是的,这很好,但如果您有很多文本框,我认为这将是正确的做法。由于只有 4 个文本框,并假设它们的名称是 textbox1、textbox2 等。但是如果文本框的数量很多并且它们没有相同的名称,它会有所帮助。它不仅检查空文本框,还可以检查任何控件及其属性,例如选中哪个单选按钮或启用/禁用任何控件。您需要进行一些小的更改,例如将 msforms.textbox 替换为您的控件类型,并在 if 条件内添加您的条件。

    Private Sub UserForm_Initialize()
    Dim ctrl As Control
    Dim x As Variant
    Dim z As msforms.TextBox
    x = 0
        For Each ctrl In frmtest.Controls
            If TypeOf ctrl Is msforms.TextBox Then
                Set z = ctrl
                x = x + CBool(Len(z.Text))
            End If
         Next
         CommandButton1.Enabled = x
    

    结束子

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多