Tony
Tony

Reputation: 75

How to go to the next step in VBA if a condition is not met

Noob here, not sure if my title makes sense so I'll give it a better shot here. I have a userform that I have a bunch of check boxes in. I want to group certain checked boxes in to a string and output them to a cell in excel (I have that part figured out). What is happening is that when I don't have any boxes checked in the userform it errors out. I have an idea why (the delete last comma code I'm using I think is the problem), but what I can't figure out is how can I just "skip" the remove comma part if the condition of the string is empty and go to the next section. I was thinking of using the GoTo function but not sure if it is what I should be using or is the most appropriate function... I'll include my code to help out too. Thanks for any help, and I'm sure that there is plenty of code housekeeping I can do...

Dim luLi As String
Dim kdBl As String

'Gather check box information for the luLi Symptoms
    If Chk_allergies.Value = True Then
    luLi = "Allergies, "
    End If
If Chk_asthma.Value = True Then
    luLi = luLi & "Asthma, "
    End If
If Chk_freqcolds.Value = True Then
    luLi = luLi & "Frequent Colds, "
    End If
If Chk_persiscough.Value = True Then
    luLi = luLi & "Persistant Cough, "
    End If
If Chk_sinus.Value = True Then
    luLi = luLi & "Sinus Problems, "
    End If
' If luLi = "" Then GoTo  <-- Couldn't figure out how to use this...
' End If
'deleting comma and space, the 2 characters at the end of luLi
    luLi = Left(luLi, Len(luLi) - 2)
Sheet1.Cells(lRow, 20) = luLi

'Gather check box information for the kiBl Symptoms
If Chk_arthritis.Value = True Then
    kdBl = "Arthritis, "
   End If
If Chk_asthma.Value = True Then
    kdBl = "Asthma, "
   End If
'If kdBl = "" Then GoTo <-- Not sure if this is the best option...
' End If
'deleting comma and space, the 2 characters at the end of kdBl
   kdBl = Left(kdBl, Len(kdBl) - 2)
Sheet1.Cells(lRow, 21) = kdBl

Upvotes: 1

Views: 2513

Answers (2)

acenturyandabit
acenturyandabit

Reputation: 1408

If no answers are checked, luLi or kdBl will be NULL and Left'ing them will cause errors. Try setting luLi=", " before anything else, so that the Left can still evaluate it.(and the same for kdbl as well.)

If that doesn't work set luLi=", "(two spaces) so that left can return something.

Upvotes: 0

Ken White
Ken White

Reputation: 125671

You're very close. What you need to do is just delete the last comma if the string is not empty:

If luLi <> "" Then 
    luLi = Left(luLi, Len(luLi) - 2)
End If

Upvotes: 2

Related Questions