0

如何缩短我的 if 语句?有没有其他方法可以缩短它??

F = Strt
E = Strt + A1
I = Strt + A1 + A2
A = Strt + A2 + A1 + A3
b = Strt + A2 + A1 + A3 + A4
c = Strt + A1 + A2 + A3 + A4 + A5
D = Strt + A1 + A2 + A3 + A4 + A5 + A6
G = Strt + A1 + A2 + A3 + A4 + A5 + A6 + A7
H = Strt + A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8
J = Strt + A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9


    If F >= Row Then
    asd = 0
    ElseIf E >= Row Then
    asd = 1
    ElseIf I >= Row Then
    asd = 2
    ElseIf A >= Row Then
    asd = 3
    ElseIf b >= Row Then
    asd = 4
    ElseIf c >= Row Then
    asd = 5
    ElseIf D >= Row Then
    asd = 6
    ElseIf G >= Row Then
    asd = 7
    ElseIf H >= Row Then
    asd = 8
    ElseIf J >= Row Then
    asd = 9
    Else
    End If

还有我的变量..我想知道我是否可以缩短它..如果回答非常感谢

4

3 回答 3

0

未测试代码,但如果需要,只需稍作修改即可使用

For i = 0 To 9
    If Str >= Row then
        asd = i 
        Exit for
    End If
    Str = Str + INDIRECT("A" + i + 1) 'assuming A1, A2 etc are cell addresses .. 
Next i
于 2013-07-11T07:45:31.903 回答
0

自从我完成 vba 以来已经有好几年了,但这是我将如何解决它的伪代码:

arr = [Strt+A1, A2, A3, A4, A5, A6, A7, A8, A9]
for i = 0; i < arr.length; i++ // assume 0-based array
    if i > 0
        arr[i] = arr[i-1]+arr[i] // sum
    if Row <= arr[i]
        asd = i
        break

这应该完全符合您的代码正在做的事情,只是更简单。基本上,您将 A1-A9 相加(从 Strt 开始),并返回 Strt <= (Strt + sum(A1..Ai)) 的索引。

我发现这段代码更具可读性,而且以后扩展起来肯定更短更容易。

于 2013-07-11T07:36:59.243 回答
0
Option Explicit
Function ASD(byval F as Range, byval E as Range, byval I as Range, _
byval A as Range, byval Row as Range) As Integer

Dim var
Dim ctr As Integer
Dim data As Variant

ctr = 0
data = Array(F.Value, E.Value, I.Value, A.Value)
For Each var In data
    If var >= Row.Value Then
       ASD = ctr
       Exit Function
    End If

    ctr = ctr + 1
Next
ASD = -1
End Function
于 2013-07-11T07:40:47.807 回答