函数永远不会执行ElseIf语句

时间:2014-05-24 00:18:22

标签: excel vba excel-vba

为excel工作一些VBA,我写了一个用户定义的函数来根据行号做一些算术。它似乎乍一看,然后我意识到无论它总是执行什么,好像第一个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

2 个答案:

答案 0 :(得分:5)

除了其他人编写的内容之外,这似乎是一个选择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

答案 1 :(得分:4)

如果不重复变量,则无法进行连续的相等测试。

需要

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

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