如果我的问题含糊,我深表歉意。我有一个代码,该代码根据聚会中的人数来计算公车旅行的费用。代码首先必须确定交易方是否低于20岁或超过120。如果要满足该条件,我想返回一个消息框,说明交易方规模要大可小,然后将价格和输入设置为0我的电子表格。退出功能不起作用,因为它完全结束了循环。我也不想退出sub,因为我需要检查多行数据并计算成本。如果我不执行任何退出操作,它将把这些值设置为0,但将继续进行计算过程并最终留下错误的值,因此我需要它跳过循环的结尾,然后再次运行循环。
谢谢!
Dim N As String 'N = Name
Dim D As Date 'D = Date
Dim P As Integer 'P = Number of people
Dim H As Single 'H = Number of hours
Dim NS As Integer 'NS = Number of Small Buses
Dim NL As Integer 'NL = Number of Large Buses
Dim BP As Currency 'BP = Base Price
Dim OH As Single 'OH = Overtime Hours
Dim OC As Currency 'OC = Overtime Charge
Dim TP As Currency 'TP = Total Price
Dim PPBR As Currency 'PPBR = Per-person Base Rate
Dim EHP As Single 'EHP = Extra Hourly Percent
Dim myRow As Integer 'helping to paste output
Dim oRow As Integer '
Do Until IsEmpty(Cells(oRow, 1))
P = Cells(oRow, 3)
H = Cells(oRow, 4)
NS = 0
NL = 0
'Checking that there is enough people to continue
If P < 20 Then
MsgBox "The Minimum # of persons is 20", , "Sorry!"
NS = 0
NL = 0
BP = 0
OH = 0
OC = 0
TP = 0
Cells(oRow, 7) = NS
Cells(oRow, 8) = NL
Cells(oRow, 9) = BP
Cells(oRow, 10) = OH
Cells(oRow, 11) = OC
Cells(oRow, 12) = TP
Exit Do
ElseIf P > 120 Then
'checking that there are not to many participants.
MsgBox "Sorry the maximum amount of Persons is 120!", , "Sorry!"
NS = 0
NL = 0
BP = 0
OH = 0
OC = 0
TP = 0
Cells(oRow, 7) = NS
Cells(oRow, 8) = NL
Cells(oRow, 9) = BP
Cells(oRow, 10) = OH
Cells(oRow, 11) = OC
Cells(oRow, 12) = TP
Exit Do
'solving how many busses will be needed based on the amount of people
ElseIf P >= 20 And P <= 25 Then
NS = 1
ElseIf P >= 26 And P <= 50 Then
NS = 2
ElseIf P >= 51 And P <= 60 Then
NL = 1
ElseIf P >= 61 And P <= 85 Then
NS = 1
NL = 1
ElseIf P >= 86 And P <= 120 Then
NL = 2
End If
'calculate base price
BP = P * PPBR
'Calculating with no overtime
If H < 5 Then
TP = BP
OC = 0
OH = 0
Cells(oRow, 7) = NS
Cells(oRow, 8) = NL
Cells(oRow, 9) = BP
Cells(oRow, 10) = OH
Cells(oRow, 11) = OC
Cells(oRow, 12) = TP
'calculating overtime over 9 hours (which will only be 4 hours)
ElseIf H > 9 Then
OH = 4
OC = BP * OH * EHP
TP = OC + BP
Cells(oRow, 7) = NS
Cells(oRow, 8) = NL
Cells(oRow, 9) = BP
Cells(oRow, 10) = OH
Cells(oRow, 11) = OC
Cells(oRow, 12) = TP
'calculating overtime between 0 and 4 hours
Else
OH = H - 5
OC = BP * OH * EHP
TP = OC + BP
Cells(oRow, 7) = NS
Cells(oRow, 8) = NL
Cells(oRow, 9) = BP
Cells(oRow, 10) = OH
Cells(oRow, 11) = OC
Cells(oRow, 12) = TP
End If
oRow = oRow + 1
NS = 0
NL = 0
BP = 0
OH = 0
OC = 0
TP = 0
Loop
End Sub
答案 0 :(得分:0)
VBA中此类问题的典型解决方案是重组代码,以使计算部分与迭代单元格的部分在单独的函数中。然后,如果不符合正确的条件,就可以安全地退出计算功能,而不会影响迭代。