VBA代码检查文本框是否为空,如果不允许用户继续



我有一个带有多个文本框的用户形式。如果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是否值。另外,当我在消息框中单击"确定"时,该子继续运行并将文本框的值插入工作表。如果出现消息框,我想这不会发生。

感谢提前的任何帮助!

使用And/Or布尔逻辑时,有时需要括号以确保正确评估它。当时:

If Con1 And Con2 Or Con3 Then

正在被解释:

  • Con1Con2 true?

  • Con3是真的吗?

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

If Con1 And (Con2 Or Con3) Then

将被解释为:

  • Con1是真的吗?

  • Con2还是Con3 True?

,如果我正确理解您的问题,那就是您的目标。但是,这确实意味着,如果TextBox2Textbox3都是空的,那么TextBox1是否有任何东西都没有关系。MsgBox 不会发生,其余代码将。


进一步的布尔分析:

由于 Con1 - Len(TextBox1) = ""-始终解决False (请参阅下面的注1(And检查 - Con1 And Con2始终是false。因此,if语句可以解决到true的唯一方法是Con3解决至True

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


注意:

  1. Len(TextBox1) = ""始终等于false。Len()返回一个数字而不是字符串。我认为您可以合并两种用于检查一个空字符串的方法。TextBox1.Value = ""Len(TextBox1.Value) = 0都可以使用;但是,组合没有意义。虽然我大部分时间都在键入答案之前就键入答案。

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

  3. 您对TextBox1内容的当前检查仅在TextBox1为空时才会导致MsgBox。此不包括白色空间字符,例如空间。如果您还想要MsgBox时只有白色空间字符,则应该尝试以下操作:Len(Trim(TextBox1.Value)) = 0而不是以前拥有的东西(Len(TextBox1) = ""(。

    您可以在此处查看其他建议,如果您不想触发MsgBox,则可能还要考虑在TextBox2TextBox3上添加类似的检查太空字符。


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

替换:

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

with:

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

相关内容

最新更新