For中的VBA If语句(即使满足If条件也将运行)

时间:2019-11-12 20:43:55

标签: vba ms-access

我对VBA还是很陌生,即使满足条件也无法运行Else语句。

可以肯定这是由于If语句位于For&Next

For iCnt = 1 To Len(Firstname)
    If IsNumeric(Mid(Firstname, iCnt, 1)) Then
        MsgBox "The Firstname cannot contain Numeric values"
    ElseIf Len(Firstname) > 100 Then
        MsgBox "The Firstname exceeds the character limit (100)"
    Else
        Sheet3.Cells(lRow, 2).Value = Me.Firstname.Value
    End If
Next iCnt

请问如何解决此问题的任何建议?

3 个答案:

答案 0 :(得分:3)

真的,您只希望第一个条件存在于该FOR循环中。其余部分应在之后进行测试,并且前提是该第一个条件永远不会跳闸。

请考虑:

Dim nameHasNumbers as boolean: nameHasNumbers = False
For iCnt = 1 To Len(Firstname)
    If IsNumeric(Mid(Firstname, iCnt, 1)) Then
        'number found toggle flag and exit the loop
        nameHasNumbers = True
        exit For
    End If    
Next iCnt

'Now alert the user or update the name cell
If nameHasNumbers Then
    MsgBox "The Firstname cannot contain Numeric values"
ElseIf Len(Firstname) > 100 Then
    MsgBox "The Firstname exceeds the character limit (100)"
Else
    Sheet3.Cells(lRow, 2).Value = Me.Firstname.Value
End If

答案 1 :(得分:1)

对于名称中的每个字母,您都会使Else发生。需要重组整个事情。我会将检查放入函数中,然后根据该结果执行其他工作。如果您需要一条消息通知用户名称无效的原因,请将其添加到函数中。然后,您的函数可以在其他条件下进行其他测试,而不会影响您的调用代码。

Private Function IsValidName(ByVal value As String) As Boolean
    If Len(value) > 100 Then
        IsValidName = False
        Exit Function
    Else
        Dim charCounter As Long
        For charCounter = 1 To Len(value)
            If IsNumeric(Mid(value, charconter, 1)) Then
                IsValidName = False
                Exit Function
            End If
        Next
        IsValidName = True
    End If
End Function

答案 2 :(得分:1)

当您要检查字符串是否包含数字时,可以将其与匹配数字的Like模式进行比较:FirstName Like "*[0-9]*"

该方法比循环检查每个字符是否为数字的字符串更简单。而且,由于它不需要For循环,因此应该更容易避免代码示例中的逻辑错误。 (只要字符串长度不超过100个字符,它就会为Sheet3.Cells(lRow, 2).Value中包含的每个非数字字符再次向FirstName写一个值。)

If FirstName Like "*[0-9]*" Then
    MsgBox "The Firstname cannot contain Numeric values"
ElseIf Len(FirstName) > 100 Then
    MsgBox "The Firstname exceeds the character limit (100)"
Else
    Sheet3.Cells(lRow, 2).Value = Me.FirstName.Value
End If