Tim
Tim

Reputation: 105

Length checking in VBA with null

I have some code that is meant to check the length of the values in the text boxes, and if any of the boxes has no content the length of the string is 0 (or null). Here is the code:

If (Len(Form_MainScreen.Ctl48.Value) Or Len(Form_MainScreen.Ctl49.Value) Or _
    Len(Form_MainScreen.Ctl50.Value) Or Len(Form_MainScreen.Ctl51.Value) Or _
    Len(Form_MainScreen.Ctl52.Value) Or Len(Form_MainScreen.Ctl53.Value) Or _
    Len(Form_MainScreen.Ctl54.Value) = 0) Then
              Do X
Else
              Do Y
End If

When one string is blank, the length check becomes "null" and so does the whole statement. But if the length checks are all not null, the if statement becomes a "1" and then procedes to execute the Do X procedure again.

Any idea of what I can do?

Thanks, Tim

Upvotes: 1

Views: 1866

Answers (2)

anonymous
anonymous

Reputation: 11

If (Len(Form_MainScreen.Ctl48.Value)=0 Or Len(Form_MainScreen.Ctl49.Value)=0 Or _
    Len(Form_MainScreen.Ctl50.Value)=0 Or Len(Form_MainScreen.Ctl51.Value)=0 Or _
    Len(Form_MainScreen.Ctl52.Value)=0 Or Len(Form_MainScreen.Ctl53.Value)=0 Or _
    Len(Form_MainScreen.Ctl54.Value) = 0) Then
    Do X
Else
    Do Y
End If

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37543

Your code snippet doesn't make much sense to me, but if you're using vb.net and you want "X" to execute if ANY of the values is null or 0 length then you could do the following:

If (String.IsNullOrEmpty(Form_MainScreen.Ctl48.Value) OrElse String.IsNullOrEmpty() OrElse _
    String.IsNullOrEmpty(Form_MainScreen.Ctl50.Value) OrElse String.IsNullOrEmpty(Form_MainScreen.Ctl51.Value) OrElse _
    String.IsNullOrEmpty(Form_MainScreen.Ctl52.Value) OrElse String.IsNullOrEmpty(Form_MainScreen.Ctl53.Value) OrElse _
    String.IsNullOrEmpty(Form_MainScreen.Ctl54.Value)) Then
    X()
Else
    Y()
End If 

Using String.IsNullOrEmpty is a built-in function that will handle both conditions without exception. Using the OrElse conditional will allow slightly faster processing in that it will stop executing the conditional expressions once it receives a valid match. Using simply Or requires all conditional expressions to be evaluated even if it's not necessary.

Upvotes: 3

Related Questions