Excel VBA 错误:在没有 For 的情况下下一个编译错误
Posted
技术标签:
【中文标题】Excel VBA 错误:在没有 For 的情况下下一个编译错误【英文标题】:Excel VBA Error: Compile Error Next without For 【发布时间】:2017-11-01 10:17:27 【问题描述】:下面是我的代码。当我运行它时,它显示:
在没有 For 的情况下编译错误 Next。
请帮忙!
Sub W09T1()
Dim i As Integer
Dim FinalRow As Integer
Dim thisCategory As String, thisProduct As String
Dim thisQty As Integer
Dim Sale As Boolean
Dim discount As Single
With Sheets("sheet1")
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
Range("D1").Value = "Discount"
For i = 2 To FinalRow
thisCategory = Cells(i, 1).Value
thisProduct = Cells(i, 2).Value
thisQty = Cells(i, 3).Value
'insert select case to determine if the product
'is on sale here
'Use If-Then-Else and/or Select Case to
'determine the discount based on product
'category and discount rules
If Sale Then
discount = 0.25
Else
If thisCategory = "Fruit" Then
Select Case thisQty
Case Is < 5
discount = 0
Case 5 To 20
discount = 0.1
Case Is > 20
discount = 0.15
End Select
ElseIf thisCategory = "Herbs" Then
'insert select case to determine
'discount of Herbs here
ElseIf thisCategory = "Vegetables" Then
'insert If-Then-Else and/or Select
'Case to determine discount of
'Vegetables
'insert discount to be displayed in column D
If Sale Then
Cells(i, 1).Resize(1, 4).Interior.Color = vbYellow
End If
Next i
End With
End Sub
【问题讨论】:
(欢迎使用 SO!)(尝试“注释掉”部分代码。)(检查哪些语句具有END
以及您正在使用它。)
【参考方案1】:
你缺少 2 个 End If
的
有时候你会错过一个
如果结束
以
结尾结束循环
等
在For..Next
循环中,VBA 会混淆到底是哪一个问题,并错误地描述了错误。
您的所有If
和ElseIf'
都需要和End If
。就个人而言,我避免使用ElseIf
,因为与使用漂亮整洁的If..Then..Else..End If
块(根据需要嵌套)相比,它们使代码更难理解。
您的代码:
我用第二个Select..Case
声明替换了If-Else-Elseif-Elseif
的东西:
Sub W09T1()
Dim i As Integer
Dim FinalRow As Integer
Dim thisCategory As String, thisProduct As String
Dim thisQty As Integer
Dim Sale As Boolean
Dim discount As Single
With Sheets("sheet1")
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
Range("D1").Value = "Discount"
For i = 2 To FinalRow
thisCategory = Cells(i, 1).Value
thisProduct = Cells(i, 2).Value
thisQty = Cells(i, 3).Value
'insert select case to determine if the product
'is on sale here
'Use If-Then-Else and/or Select Case to
'determine the discount based on product
'category and discount rules
If Sale Then
discount = 0.25
Else
Select Case thisCategory
Case "Fruit"
Select Case thisQty
Case Is < 5
discount = 0
Case 5 To 20
discount = 0.1
Case Is > 20
discount = 0.15
End Select
Case "Herbs"
'insert select case to determine
'discount of Herbs here
Case "Vegetables"
'insert If-Then-Else and/or Select
'Case to determine discount of
'Vegetables
'insert discount to be displayed in column D
Case Else
'you could optionally add code here that will run
' if "thisCategory" isn't Fruit,Herbs or Vegetables
End Select
End If
If Sale Then
Cells(i, 1).Resize(1, 4).Interior.Color = vbYellow
End If
Next i
End With
End Sub
【讨论】:
以上是关于Excel VBA 错误:在没有 For 的情况下下一个编译错误的主要内容,如果未能解决你的问题,请参考以下文章