VBA if语句缩短

时间:2013-07-11 07:24:13

标签: vba loops if-statement

如何缩短我的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

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

3 个答案:

答案 0 :(得分: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为&lt; =(Strt + sum(A1..Ai))的索引。

我觉得这段代码更具可读性,而且它更加简短,以后更容易扩展。

答案 1 :(得分: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

答案 2 :(得分: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