vba - 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
请任何建议如何解决这个问题?
解决方案
实际上,您只希望该 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
推荐阅读
- grpc - 实现 gRPC 服务以替换 .NET Framework WCF 服务
- javascript - 组件中的解构道具得到不同的结果
- php - 带有附加条件的php foreach
- css - 编译的 SCSS 在这种样式上抛出错误“-ms-grid-columns: (1fr)[2];”
- python - 尝试使用 pyusb 读取 UHF 阅读器,总是返回 None
- postgresql - 为什么插入时 PostgreSQL 的默认值不起作用?
- android - Android 谷歌支付 Braintree 集成
- php - Symfony Messenger 消费者池
- javascript - 当我向应用程序(javascript 和 nodejs)中的端点发出请求时,在邮递员中指定源头没有任何作用
- c - 为什么while循环之后的任何代码都没有输出?