首页 > 解决方案 > For 中的 VBA If 语句(即使满足 If 条件也会运行)

问题描述

我对 VBA 很陌生,即使满足 If 条件,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

请任何建议如何解决这个问题?

标签: vbams-access

解决方案


实际上,您只希望该 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

推荐阅读