2016-04-14 78 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