首页 文章

VBA代码检查TextBox是否为空,如果是,则不允许用户继续

提问于
浏览
0

我有一个带有多个文本框的用户表单 . 如果TextBox2和/或TextBox3中有任何内容,我想要一个消息框,但TextBox1中没有任何内容 . 如果发生这种情况,如果用户无法继续,我也会喜欢它 .

这是我目前的代码:

Private Sub SubmitCommandButtom_Click()
If Len(TextBox1) = "" And Len(TextBox2) > 0 Or Len(TextBox3) > 0 Then
    MsgBox "Unit Number must be entered to continue!"
End If
Sheets("Uneven Split Job Aid").Range("A2") = TextBox1.Value
Sheets("Uneven Split Job Aid").Range("B2") = TextBox2.Value
Sheets("Uneven Split Job Aid").Range("C2") = TextBox3.Value

此代码当前仅在Textbox3中存在值而不在TextBox1中时生成消息框,如果TextBox2中有任何内容则无关紧要 . 我想要检查TextBox2的值 . 此外,当我在消息框上单击“确定”时,Sub继续运行并将TextBox的值插入到工作表中 . 如果出现消息框,我想不会发生这种情况 .

在此先感谢您的帮助!

2 回答

  • 0

    使用 And / Or 布尔逻辑时,有时需要括号以确保正确计算它 . 当它是:

    If Con1 And Con2 Or Con3 Then
    

    它正在被解释:

    • Con1Con2 都是真的吗?

    要么

    • Con3 是真的吗?

    所以,我添加了括号来阅读:

    If Con1 And (Con2 Or Con3) Then
    

    这将被解释为:

    • Con1 是真的吗?

    • Con2 还是 Con3 是真的?

    如果我正确理解你的问题,那就是你的目标逻辑 . 但是,这确实意味着如果 TextBox2Textbox3 都为空,那么 TextBox1 是否有任何内容都无关紧要; MsgBox won't 发生了,其余的代码将会发生 .


    Further Boolean Analysis:

    由于 Con1 - Len(TextBox1) = "" - 始终解析为 False (参见下面的注释1), And 检查 - Con1 And Con2 始终为 false . 因此, if 语句可以解析为 true 的唯一方法是 Con3 解析为 True .

    由于 Con3Len(TextBox3) > 0 ,整个if语句取决于 TextBox3 中文本的长度!


    Notes:

    • Len(TextBox1) = "" 将始终等于false . Len() 返回的数字不是字符串 . 我认为你偶然结合了两种检查空字符串的方法 . TextBox1.Value = ""Len(TextBox1.Value) = 0 可以工作;但是,这种组合没有意义 . 虽然在我 grab 这个之前我花了大部分时间打了我的答案 .

    • 最好在访问内容时使用 TextBox.ValueTextBox.Text 而不是 TextBox .

    • 仅当 TextBox1 为空时,对 TextBox1 内容的当前检查才会导致 MsgBox . 这个 excludes 空格字符,如空格 . 如果在只有空格字符时也需要 MsgBox ,则应该尝试类似: Len(Trim(TextBox1.Value)) = 0 而不是之前的( Len(TextBox1) = "" ) .

    你可以查看其他的建议here你可能还想考虑在 TextBox2TextBox3 上添加类似的检查,如果你不想触发 MsgBox ,如果它们有空白字符,但不是任何非空白字符 .


    Private Sub SubmitCommandButtom_Click()
    
    'Changed Len(TextBox1) = "" to Len(TextBox1.Value) = 0 as per explanation above.
    'Added .Value to length checks
    If Len(TextBox1.Value) = 0 And (Len(TextBox2.Value) > 0 Or Len(TextBox3.Value) > 0) Then
        MsgBox "Unit Number must be entered to continue!"
    Else
        Sheets("Uneven Split Job Aid").Range("A2") = TextBox1.Value
        Sheets("Uneven Split Job Aid").Range("B2") = TextBox2.Value
        Sheets("Uneven Split Job Aid").Range("C2") = TextBox3.Value
        'And any other code ....
    End If
    
  • 2

    更换:

    If Len(TextBox1) = "" And Len(TextBox2) > 0 Or Len(TextBox3) > 0 Then
    

    有:

    If Len(TextBox1) = "" And Len(TextBox2 & TextBox3)  > 0 Then
    

相关问题