一次测试多个文本框中是否有空格



我想检查表单上的三个不同文本框(但不是全部(,看看是否有空白。与电子表格上的"If IsBlank"相当。从我读到的内容来看,IsEmpty似乎不能这样使用?我一直在玩IsNull,但还没有找到一个合适的语法来允许它工作。肯定有一些简单甚至标准的方法可以做到这一点吗?也许还有其他我从未听说过的功能?

(我知道我可以使用If Txtbx1.value = "" Or If... (etc.)--我正在寻找一种更短、更优雅的方式。(

谢谢!

考虑使用OR

Sub dural()
If Txtbx1.Value = "" Or Txtbx2.Value = "" Or Txtbx3.Value = "" Then
MsgBox "at least one empty"
End If
End Sub

匹配与文本框阵列的壮举。IsError、VarType和TypeName

所有代码都在用户表单代码表中,并通过用户表单上的命令按钮运行,其中还有三个文本框。

在第一个代码中,Match的结果被传递给var(变体(变量,并进行进一步评估。如果至少有一个文本框没有值("或vbNullString(,var将返回第一个找到的空文本框的位置,基于1,即第一个为1,第二个为2等。与基于0的数组不同,即第一元素为0,第二元素为1等。

第二个代码介绍了第一个代码中研究的三个选项。

第三个代码是一个没有变量的"坏"代码。

Sub TextBoxFun()
Dim vntTB As Variant    ' Text Box Array
Dim var As Variant      ' Match Variant
Dim strTB As String     ' Pass String
Dim lngTB As Long       ' Pass Long
' Pass TextBoxes to Text Box Array.
vntTB = Array(TextBox1, TextBox2, TextBox3)
' Either:
var = Application.Match("", vntTB, 0)
' Or:
'var = Application.Match(vbNullString, vntTB, 0)
Debug.Print String(10, "'")
Debug.Print "IsError(var)  = " & IsError(var)    ' True
Debug.Print "VarType(var)  = " & VarType(var)    ' 10 or vbError
Debug.Print "TypeName(var) = " & TypeName(var)   ' Error
Debug.Print String(10, "'")
' Line of Code / vbNullString Found ? >>> '  True        False
Debug.Print var                           '     1
' Depending on the first position of      '     2
' the found vbNullString or "".           '     3   Error 2042
lngTB = IsError(var): Debug.Print lngTB   '     0           -1
lngTB = VarType(var): Debug.Print lngTB   '     5           10
'lngTB = TypeName(var): Debug.Print lngTB '  Nope         Nope
' TypeName returns always a string.
strTB = IsError(var): Debug.Print strTB   ' False         True
strTB = VarType(var): Debug.Print strTB   '     5           10
strTB = TypeName(var): Debug.Print strTB  ' Double       Error
End Sub
Sub TextBoxFunConclusion()
Dim vntTB As Variant    ' Text Box Array
' Pass TextBoxes to Text Box Array.
vntTB = Array(TextBox1, TextBox2, TextBox3)
If IsError(Application.Match("", vntTB, 0)) Then
Debug.Print "No 'empty' text boxes (via IsError)."
Else
Debug.Print "At least one 'empty' text box (via IsError)."
End If
If VarType(Application.Match("", vntTB, 0)) = 10 Then
Debug.Print "No 'empty' text boxes (via VarType)."
Else
Debug.Print "At least one 'empty' text box (via VarType)."
End If
If TypeName(Application.Match("", vntTB, 0)) = "Error" Then
Debug.Print "No 'empty' text boxes (via TypeName)."
Else
Debug.Print "At least one 'empty' text box (via TypeName)."
End If
End Sub
Sub TextBoxFunMyChoice()
If IsError(Application.Match("", Array(TextBox1, TextBox2, TextBox3), 0)) _
Then
Debug.Print "No 'empty' text boxes (via IsError)."
Else
Debug.Print "At least one 'empty' text box (via IsError)."
End If
End Sub

Private Sub CommandButton1_Click()
TextBoxFun
End Sub
Private Sub CommandButton2_Click()
TextBoxFunConclusion
End Sub
Private Sub CommandButton3_Click()
TextBoxFunMyChoice
End Sub

最新更新