使用 And / Or 布尔逻辑时,有时需要括号以确保正确计算它 . 当它是:
If Con1 And Con2 Or Con3 Then
它正在被解释:
Con1 和 Con2 都是真的吗?
要么
Con3 是真的吗?
所以,我添加了括号来阅读:
If Con1 And (Con2 Or Con3) Then
这将被解释为:
Con1 是真的吗?
和
是 Con2 还是 Con3 是真的?
如果我正确理解你的问题,那就是你的目标逻辑 . 但是,这确实意味着如果 TextBox2 和 Textbox3 都为空,那么 TextBox1 是否有任何内容都无关紧要; MsgBox won't 发生了,其余的代码将会发生 .
Further Boolean Analysis:
由于 Con1 - Len(TextBox1) = "" - 始终解析为 False (参见下面的注释1), And 检查 - Con1 And Con2 始终为 false . 因此, if 语句可以解析为 true 的唯一方法是 Con3 解析为 True .
由于 Con3 是 Len(TextBox3) > 0 ,整个if语句取决于 TextBox3 中文本的长度!
Notes:
Len(TextBox1) = "" 将始终等于false . Len() 返回的数字不是字符串 . 我认为你偶然结合了两种检查空字符串的方法 . TextBox1.Value = "" 或 Len(TextBox1.Value) = 0 可以工作;但是,这种组合没有意义 . 虽然在我 grab 这个之前我花了大部分时间打了我的答案 .
最好在访问内容时使用 TextBox.Value 或 TextBox.Text 而不是 TextBox .
仅当 TextBox1 为空时,对 TextBox1 内容的当前检查才会导致 MsgBox . 这个 excludes 空格字符,如空格 . 如果在只有空格字符时也需要 MsgBox ,则应该尝试类似: Len(Trim(TextBox1.Value)) = 0 而不是之前的( Len(TextBox1) = "" ) .
你可以查看其他的建议here你可能还想考虑在 TextBox2 和 TextBox3 上添加类似的检查,如果你不想触发 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