我在代码的以下部分中收到编译错误“Else without If”。问题是什么,我该如何解决?
If InStr(1, Worksheets("Raw data").Cells(i, 3), "1M") Then Call RowCopyPaste("AS-001", i, counter1M)
counter1M = counter1M + 1
ElseIf InStr(1, Worksheets("Raw data").Cells(i, 3), "2M") Then Call RowCopyPaste("AS-001", i, counter2M)
counter2M = counter2M + 1
ElseIf InStr(1, Worksheets("Raw data").Cells(i, 3), "3M") Then Call RowCopyPaste("AS-001", i, counter3M)
counter3M = counter3M + 1
End If
答案 0 :(得分:2)
如果比较可以与单个命令存在于同一行,但不能像您一样。您的每个条件的两个命令应该更像是以下内容。
If InStr(1, Worksheets("Raw data").Cells(i, 3), "1M") Then
Call RowCopyPaste("AS-001", i, counter1M)
counter1M = counter1M + 1
ElseIf InStr(1, Worksheets("Raw data").Cells(i, 3), "2M") Then
Call RowCopyPaste("AS-001", i, counter2M)
counter2M = counter2M + 1
ElseIf InStr(1, Worksheets("Raw data").Cells(i, 3), "3M") Then
Call RowCopyPaste("AS-001", i, counter3M)
counter3M = counter3M + 1
End If
以下内容可以单独使用,但不能与其他ElseIf
命令一起使用。
If InStr(1, Worksheets("Raw data").Cells(i, 3), "1M") Then Call RowCopyPaste("AS-001", i, counter1M)
如果您还有其他条件可以覆盖,可以尝试将其作为Select Case statement。
答案 1 :(得分:2)
或者,您可以将嵌套的If替换为Select Case,甚至将Instr()替换为Like运算符:
Select Case True
Case Worksheets("RawData").Cells(1, 1) Like "*1M*"
Call RowCopyPaste("AS-001", i, counter1M)
counter1M = counter1M + 1
Case Worksheets("RawData").Cells(1, 1) Like "*2M*"
Call RowCopyPaste("AS-001", i, counter2M)
counter2M = counter2M + 1
Case Worksheets("RawData").Cells(1, 1) Like "*3M*"
Call RowCopyPaste("AS-001", i, counter3M)
counter3M = counter3M + 1
Case Else
'...
End Select