请协助运行以下Excel宏。我想我错过了一些东西。逻辑不起作用。
Sub RiskGrade()
Dim Value1 As String
Sheets("Sheet1").Select
If (Cells(10, 2) = "BX") Then Cells(12, 4) = -8
Exit Sub
ElseIf (Cells(10, 2) = "GX") Then Cells(12, 4) = -7
Exit Sub
Else
For i = 12 To 14
Value1 = Right(Trim(Sheet1.Cells(i, 2)), 1)
'MsgBox Value1
Select Case Value1
Case "W"
Cells(i, 4) = 1
Case "H", "S", "R", "F", "G"
Cells(i, 4) = 2
Case "D"
Cells(i, 4) = 3
Case "C"
Cells(i, 4) = 4
Case "B"
Cells(i, 4) = 5
Case "A"
Cells(i, 4) = 6
Case "*"
Cells(i, 4) = 7
Case "M"
Cells(i, 4) = 8
Case "E"
Cells(i, 4) = 9
Case OTHER
Cells(i, 4) = -9
End Select
Exit For
Next i
End If
End Sub
答案 0 :(得分:9)
你已经启动了一个IF语句,并在同一行添加了一个动作,这意味着它不会期望在此之后出现END IF或ELSE。
在VB中
IF条件然后行动
是一个IF语句。
考虑
If (Cells(10, 2) = "BX") Then
Cells(12, 4) = -8
Exit Sub
ElseIf (Cells(10, 2) = "GX") Then
Cells(12, 4) = -7
Exit Sub
...
答案 1 :(得分:3)
Case OTHER
应为Case Else
Exit For
将在第一次通过后终止循环,因此需要删除或更改为您希望处理中止的位置 If ... Then
应为多行或单行。
多行:
If (Cells(10, 2) = "BX") Then
Cells(12, 4) = -8
Exit Sub
ElseIf ...
单行:
If (Cells(10, 2) = "BX") Then Cells(12, 4) = -8 : Exit Sub
ElseIf ...
(注意使用:
分隔同一If
语句中的命令)
答案 2 :(得分:0)
您应该使用OPTION EXPLICIT
,因为当拼写错误应用于关键字时,它有助于发现错误。
在当前形状中,您使用Case OTHER
Case Else
指定了意外行为,VBA中没有关键字OTHER
,因此OTHER
被解释为{Variant
的变量1}}数据类型,但Case Else
将被正确解释为"在其他情况下执行..."。
在Exit For
Select
停止宏执行后i=12
使用Option Explicit
Sub RiskGrade()
Dim Value1 As String
Sheets("Sheet1").Select
If (Cells(10, 2) = "BX") Then
Cells(12, 4) = -8
Exit Sub
ElseIf (Cells(10, 2) = "GX") Then
Cells(12, 4) = -7
Exit Sub
Else
For i = 12 To 14
Value1 = Right(Trim(Sheet1.Cells(i, 2)), 1)
Debug.Print Value1 'CTRL+G for immediate window
Select Case Value1
Case "W"
Cells(i, 4) = 1
Case "H", "S", "R", "F", "G"
Cells(i, 4) = 2
Case "D"
Cells(i, 4) = 3
Case "C"
Cells(i, 4) = 4
Case "B"
Cells(i, 4) = 5
Case "A"
Cells(i, 4) = 6
Case "*" 'I don't know what behaviour in will cause, does it spot '*' only, or any char
Cells(i, 4) = 7
Case "M"
Cells(i, 4) = 8
Case "E"
Cells(i, 4) = 9
Case Other ' not OTHER
Cells(i, 4) = -9
End Select
'Exit For ' - why exit after first iteration - guess it's unnecessary procedure ?
Next i
End If
,则不会应用13和14。
{{1}}
End Sub
答案 3 :(得分:-1)
如果同时删除“exit sub”,它应该可以正常工作。 使用“退出子”,似乎你正在关闭你没有“结束if”