VBA中空string的条件
如何检查stringvariables在vba中是否为空?
如果:
Dim StrFile1 As String, StrFile2 As String Dim Text3 As String Dim Len1 as Integer, Len2 As Integer With NewMail Text3 = Cells(i, 3).Value StrPath = Cells(i, 2).Value & Text3 Text = Cells(i, 1).Value .Subject = ' adds the data in column3 with space as subject .From = .To = Text .BCC = "" .TextBody = StrFile1 = Dir(StrPath & "*.txt") Len1 = Len(StrFile1) Do While Len(StrFile1) > 0 .AddAttachment StrPath & StrFile1 StrFile1 = Dir Loop StrFile2 = Dir(StrPath & "*.pdf") Len2 = Len(StrFile2) Do While Len(StrFile2) > 0 .AddAttachment StrPath & StrFile2 StrFile2 = Dir Loop If (Len1 & Len2) = 0 Then GoTo Last '.AddAttachment Text3 .Send End With i = i + 1 Loop Last: End With i = i + 1 Loop
现在我想同时检查Len1和Len2是否为0,如果是的话我想去Last。
当我使用这个代码时,我收到一条消息/编译错误“ 想要结束而没有” ,我不知道是否
If (Len1 & Len2) = 0 Then GoTo Last
这是一个正确的代码。 我需要申报标签最后?
你有很多方法可以做到这一点,如下所示:
Dim StrFiles As String StrFiles = Trim(StrFile1 & StrFile2) If IsEmpty(StrFiles) Then If StrFiles = vbNullString Then If StrFiles = "" Then If StrFiles = Empty Then If Len(StrFiles) = 0 Then
您可以使用+ operator
来检查2个string是否为您的代码的空引用,因为Len Function
返回的整数包含string中的字符数
If (Len1 + Len2) = 0 Then
您可以使用Trim(strFile1 & vbNullString) = vbNullString
来检查string是否为空。
所以:
If Trim(strFile1 & vbNullString) = vbNullString Then Debug.print "Empty String!" End If
感谢@ LordPeter
对于VBA is.empty
不存在,但第二个选项有效。
或者,你可以写:
(strFile1 & strFile2) = vbNullString
要么
(strFile1 & strFile2) = ""
另一种方式是:
If Len(strFile1 & strFile2) > 0 Then
我做了testing,以确保没有设置的string返回长度为0,这似乎是这种情况。