iF然后其他代码 - 如何让这个运行得更快? VBA

时间:2016-04-14 17:08:24

标签: performance vba if-statement

我有一个简单的代码需要很长时间才能运行。我想知道是否有办法让这个跑得更快?也许这部分(Cells(i,“U”)。Value = Cells(n,“X”)。Value)不应该使用2次!谢谢!

For n = 3 To time_frame + 3
For i = 3 To 1002

If (Cells(i, "U").Value = Cells(n, "X").Value) And (Bed_in_use < 24) And Wait_L > 0 Then
Wait_L = Wait_L - (24 - Bed_in_use)
ElseIf (Cells(i, "U").Value = Cells(n, "X").Value) And (Bed_in_use < 24) And Wait_L <= 0 Then
Bed_in_use = Bed_in_use + 1
End If
Next i
Next n

MsgBox "The number of bed in use is " & Bed_in_use & ". There are " & Wait_L & " patients in the waiting list."

 End Sub

2 个答案:

答案 0 :(得分:2)

一些事情会加速这一点 - @jcarroll的评论中提到了第一个,将你需要的单元格拉入一个数组并使用它而不是重复调用Cells

第二个是你提到的,以一种方式构建你的If语句 你没有两次做同样的比较。例如,对于 条件......

,情况必须如此
Cells(i, "U").Value = Cells(n, "X").Value

...而总是必须为真:

Bed_in_use < 24

Bed_in_use为24(或更高)后,您可以退出循环,因为您永远不会满足IfElseIf语句。我将其重新推广为:

Dim values() As Variant
values = ActiveSheet.UsedRange  '...or whatever Range you need.

For n = 3 To time_frame + 3
    If Bed_in_use >= 24 Then Exit For
    For i = 3 To 1002
        If Bed_in_use >= 24 Then Exit For
        If values(i, 21).Value = values(n, 24).Value Then
            If Wait_L > 0 Then
                Wait_L = Wait_L - (24 - Bed_in_use)
            Else
                Bed_in_use = Bed_in_use + 1
            End If
        End If
    Next i
Next n

答案 1 :(得分:0)

我不完全确定您的代码尝试做什么。但这里有一个如何比较两个列表的示例,并跟踪总匹配。

Sub test()

    Dim arrayU() As Variant
    Dim arrayX() As Variant

    Dim LrowU As Integer
    Dim LrowX As Integer

    Dim i As Integer
    Dim j As Integer

    Dim bed_in_use As Integer

    LrowU = Columns(21).Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    LrowX = Columns(24).Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    ReDim arrayU(1 To LrowU)
    ReDim arrayX(1 To LrowX)

    For i = 1 To LrowU
        arrayU(i) = Cells(i, 21)
    Next i

    i = 1

    For i = 1 To LrowX
        arrayX(i) = Cells(i, 24)
    Next i

    i = 1
    j = 1

    For i = 1 To LrowX
        For j = 1 To LrowU
            If arrayX(i) = arrayU(j) Then bed_in_use = bed_in_use + 1
        Next j
    Next i

    MsgBox (bed_in_use)

End Sub