Vba 函数从不执行ElseIf语句
在使用VBA for excel时,我编写了一个用户定义的函数,用于根据行号执行一些算术运算。乍一看,它似乎起了作用,然后我意识到,无论它是如何执行的,它总是好像第一个if语句是真的,并且从不考虑ElseIf的。我做错了什么Vba 函数从不执行ElseIf语句,vba,excel,Vba,Excel,在使用VBA for excel时,我编写了一个用户定义的函数,用于根据行号执行一些算术运算。乍一看,它似乎起了作用,然后我意识到,无论它是如何执行的,它总是好像第一个if语句是真的,并且从不考虑ElseIf的。我做错了什么 Function redProfit(ByVal myRange As Range) As Long Dim rangerow As Range, baseprofit As Long Application.Volatile baseprofit
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
如果不重复变量,则无法进行连续的相等性测试 这是必须的
If (.Row = 3 or .Row = 11) Then
...
目前,您的代码是“If.Row等于3或11”。11单独处理并计算为真。如果不重复该变量,则无法进行连续的相等性测试 这是必须的
If (.Row = 3 or .Row = 11) Then
...
目前,您的代码是“If.Row等于3或11”。11被单独处理并评估为true。除了其他人所写的内容之外,这似乎是一个选择案例构造可能更可取的实例:
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
除了其他人编写的内容外,这似乎是一个选择案例构造可能更可取的实例:
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
非常感谢,在过去的两个小时里,我的谷歌搜索引擎一直在盯着我的脸,但我并没有停下来逐字读这些例子给我看的内容。谢谢你指出这一点。非常感谢,在过去的两个小时里,我的谷歌搜索引擎一直在盯着我的脸,但我并没有停下来,逐字逐句地读这些例子给我看的内容。谢谢你指出这一点。为什么有人否决了这个问题?OP的问题已明确说明,并包含相应的代码。当然,我们在早期都犯了这个错误,因为“Row=3或11”是我们用英语说的。为什么有人否决了这个问题?OP的问题已明确说明,并包含相应的代码。当然,我们在早期都犯了这个错误,因为“行等于三或十一”是我们用英语说的。