【问题标题】:Checking if some textbox is empty and then running event in VBA检查某个文本框是否为空,然后在 VBA 中运行事件
【发布时间】:2021-01-05 01:43:03
【问题描述】:

我将制作一个简单的用户表单来查找值并在 ListBox 中显示结果。 我有 15 个文本框和一个用于查找的按钮。查找的数据源始终相同。只有输入值(用于查找)才会动态。 我的想法是:

  1. 声明一个公共变量,这将是输入值
  2. 检查某个文本框是否为空
  3. 如果不是,则声明变量将为TextBox.Value(不为空)并执行查找方法

有什么问题?一般来说,我可以为所有文本框写很多代码 例如:

  If TextBox1.Value <> "" Then 
    ' execute finding method - input is TextBox1.Value
    ElseIf TextBox2.Value <> "" Then 
    ' execute finding method - input is TextBox2.Value
   ...

并生成 15x ElseIf 或第二个选项单独创建按钮。 15 个按钮看起来很有趣。

但是两种解决方案都不完美。 我该如何为此实施良好的解决方案?

【问题讨论】:

    标签: excel vba if-statement events


    【解决方案1】:

    我的想法是:

    1. 声明一个公共变量,这将是输入值
    2. 检查某个文本框是否为空
    3. 如果不是,则声明变量将为TextBox.Value(不为空)并执行查找方法

    这是你正在尝试的吗?

    Dim MyValue As String
    Dim cCont As Control
    
    '~~> Loop through all textboxes
    For Each cCont In Me.Controls
        If TypeName(cCont) = "TextBox" Then
            If Len(Trim(cCont.Value)) <> 0 Then
                '~~> Set the value and exit the loop
                MyValue = cCont.Value
            Exit For
            End If
        End If
    Next cCont
    

    【讨论】:

      【解决方案2】:

      我不确定我到底知道问题出在哪里(或者为什么您可能需要 15 个按钮...),但这应该可以:

      Dim v, i as Long
      
      For i = 1 to 15
          v = Me.Controls("TextBox" & i).Value
          If Len(v) > 0 Then Exit For
      Next i
      
      'do something with v
      

      【讨论】:

      • 我会尝试换一种说法。我有 15 个文本框,这是我寻找价值的输入。所有文本框都可以使用相同的查找方法,但不同的当然会输入数据(搜索值)。示例:TextBoxe1 - 姓名、TextBoxe2 - 姓氏、TextBoxe3 - 公司等,对于“查找”晚上的句柄,我只想使用一个按钮。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多