2016-04-14 46 views
0

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

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 
+0

你可以在行“U”和“X”创建一个数组的值,然后比较数组的值,而不是单元格的值。 – jcarroll

+0

@jcarroll好的,请你让我知道如何创建数组的值。谢谢。 – Zapata

回答

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 
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 
+0

太棒了!但如何使用“去线......”而不是使用“然后退出”?那么我可以添加Bed_in_use <24的说明吗? – Zapata

+0

@Hamidkh - 我不会用goto。如果您需要更换'Bed_in_use <24',只需将其替换为不同的条件或函数调用即可。 – Comintern