函数从不执行ElseIf语句

为excel工作一些VBA,我写了一个用户定义的函数来根据行号做一些算术。 这似乎是乍一看,然后我意识到,不pipe它总是被执行,好像第一个If语句是真实的,从不考虑ElseIf。 我究竟做错了什么?

Function redProfit(ByVal myRange As Range) As Long Dim rangerow As Range, baseprofit As Long Application.Volatile baseprofit = 3500000 With myRange If (.Row = 3 Or 11) Then redProfit = baseprofit * 0.1 ElseIf (.Row = 4 Or 10) Then redProfit = baseprofit * 0.08 ElseIf (.Row = 5 Or 9) Then redProfit = baseprofit * 0.07 ElseIf (.Row = 6 Or 8) Then redProfit = baseprofit * 0.06 ElseIf .Row = 7 Then redProfit = baseprofit * 0.05 End If End With End Function 

不能重复variables就不能进行连续的等式testing。

它需要

 If (.Row = 3 or .Row = 11) Then ... 

目前,您的代码显示“如果.Row等于3或11”。 11分开处理并评估为真。

除了别人写的东西之外,这看起来就像一个Select Case构造可能更可取的例子:

 Function redProfit(ByVal myRange As Range) As Long Dim rangerow As Range, baseprofit As Long Application.Volatile baseprofit = 3500000 Select Case myRange.Row Case 3, 11 redProfit = baseprofit * 0.1 Case 4, 10 redProfit = baseprofit * 0.08 Case 5, 9 redProfit = baseprofit * 0.07 Case 6, 8 redProfit = baseprofit * 0.06 Case 7 redProfit = baseprofit * 0.05 End Select End Function