2017-02-07 75 views
-4

感謝您提前給予幫助。我設法創建了一個宏,它在名爲「ClientTradeDetails」的工作表的O列中搜索單元格值「True」,如果單元格值爲「True」,它將佔用整行並將其粘貼到名爲「TrueValues」的工作表中。需要加速代碼(從一張紙複製/粘貼到另一張)

它的工作原理,但它非常緩慢。正如你所看到的,我的主表中有65536行數據需要經過。我想複製/粘貼是問題,但我不知道如何改變這一點,以避免複製方法。任何幫助?

Sub MoveTrue() 

Sheets("ClientTradeDetails").Select 

Dim tfCol As Range, Cell As Object 

    Set tfCol = Range("O2:O439050") 'Substitute with the range ' 

    For Each Cell In tfCol 

     If Cell.Value = "True" Then 
      Cell.EntireRow.Cut 
      Sheets("TrueValues").Select 
      ActiveSheet.Range("A65536").End(xlUp).Select 
      Selection.Offset(1, 0).Select 
      ActiveSheet.Paste 
     End If 

    Next 

End Sub 
+0

問題在於,您在單個Excel表單中包含那麼多數據,並且您期望一個宏可以彌補糟糕的數據管理選擇。 – DejaVuSansMono

+2

使用[AutoFilter方法](https://msdn.microsoft.com/en-us/library/office/aa221844.aspx)在一列上過濾true並批量傳輸值。如果需要的話,重複其他列。您目前正在搜索(針對所有意圖和目的)整個工作表。當然,你只有幾列可能包含真實的。 – Jeeped

+0

@Jeeped的意思是說我認爲用'Intersect(UsedRange,Cell.EntireRow).Cut'這樣的東西代替'Cell.Entire.Cut'。這樣你只需複製需要的列。不是整行(可能沒有填充所有列。另請參閱[避免選擇](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros )。這會大大增加你的速度,而且,根據AutoFitler值的數量也可以減慢,但肯定比循環所有這些行快。 –

回答

0

這可能有點複雜得多,你要找的,但它比複製和粘貼數據更有效率:

Sub GetTrueValues() 

Dim ws As Worksheet 
Dim arr() As Variant 
Dim arrFound() As Variant 
Dim arrOut() As Variant 

Dim i As Long 
Dim j As Long 
Dim k As Long 

Dim lConst As Long: lConst = 15 ' For the O column 

Set ws = ActiveWorkbook.Sheets("SheetName") 
arr() = ws.UsedRange.Value 

For i = LBound(arr()) To UBound(arr()) 
    If arr(i, lConst) = "True" Then 
     k = k + 1 
     ReDim arrFound(1 To k) 
     arrFound(k) = i 
    End If 
Next 

ReDim arrOut(1 To k, 1 To UBound(arr(), 2)) 
For i = 1 To UBound(arrFound()) 
    For j = LBound(arr()) To UBound(arr(), 2) 
     arrOut(i, j) = arr(arrFound(k), j) ' Using the previously stored integer, 
              ' retrieve the records of interest. 
    Next 
Next 

ActiveWorkbook.Sheets.Add 
ActiveSheet.Range("A1").Resize(UBound(arrOut(), 1), UBound(arrOut(), 2)).Value = arrOut() 

End Sub 

這個宏的主要作用是發現的記錄數具有true的值,然後將所有這些放入數組中,並將數組吐出到工作表中。您可以根據需要更改將其打印出來的部分。

相關問題