gpt4 book ai didi

vba - 函数从不执行 ElseIf 语句

转载 作者:行者123 更新时间:2023-12-04 21:09:21 25 4
gpt4 key购买 nike

为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

最佳答案

除了其他人所写的之外,这似乎是 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

关于vba - 函数从不执行 ElseIf 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com