2016-02-05 196 views
1

今天早些時候,我在開發一些代碼時會得到一些幫助,這些代碼可以獲取單元格的內容並將其放入可在被隱藏時顯示的註釋中。Excel VBA用數組替代循環以提高性能

它工作的很好,但在6000行的電子表格中可能需要一段時間。我讀here,你可以用數組邏輯代替循環邏輯來加速這個過程。

任何想法,我會開始從基於循環的基於陣列的?

Dim iCell      As Range 
On Error Resume Next 'included because of an error when the .Formula function was triggered 
    For Each iCell In Selection 
     With iCell 
      If CStr(.Value) <> "" Then 
       .ClearComments 
       .AddComment 
       .Comment.Visible = False 
       .Comment.Text Text:=CStr(.Value) 
       .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft 
       .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft '2.26 was the original height 
      End If 
      If .Formula <> "" Then 
       .ClearComments 
       .AddComment 
       .Comment.Visible = False 
       .Comment.Text Text:=CStr(.Formula) 
       .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft 
       .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft 
      End If 
     End With 
    Next 
End Sub 

與去年的時候,任何和所有幫助表示讚賞,無論是指導或例子或一個解決方案 - 我打算嘗試反向工程它來教我更多關於這個東西。謝謝!

+2

使用數組,可以'昏暗aMyArray作爲Variant','aMyArray = Selection.Value'然後通過'aMyArray環(R,C)'與限制ř ='LBound(aMyArray,1)'到'UBound(aMyArray,1)',c ='LBound(aMyArray,2)'到'UBound(aMyArray,2)'。但基於你的IF塊,它不能在Array上工作。你可以用'IsEmpty(iCell)'檢查空白單元格。您可以使用'iCell.HasFormula'來檢查它是否存儲公式或值。你現在只有公式。 – PatricK

+0

@Patrick由於OP需要添加一個評論框,所以在這裏不會有所幫助 - OP的確是數組比數據處理範圍更好。但是您需要使用範圍來添加註釋,但無法使用數組來完成。 – brettdj

回答

2

這是你如何能提高你的必要範圍內循環的例子:

  1. 使用SpecialCells對公式的工作不看每個單元格。
  2. 優化Application設置。
  3. 將隱藏註釋的行從循環中取出。

代碼

Sub Recut() 
Dim rng1 As Range 
Dim rng2 As Range 
Dim lngCalc As Long 

'look only at formulae 
On Error Resume Next 
Set rng1 = Selection.SpecialCells(xlFormulas) 
On Error GoTo 0 

If rng1 Is Nothing Then Exit Sub 

'Improve application settings for speed 
With Application 
    lngCalc = .Calculation 
    .ScreenUpdating = False 
    .Calculation = xlCalculationManual 
    .DisplayAlerts = False 
End With 

For Each rng2 In rng1.Cells 
With rng2 
     .ClearComments 
     .AddComment 
     .Comment.Text Text:=CStr(.Formula) 
     .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft 
     .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft 
End With 
Next 

'take comment display out of the loop 
Application.DisplayCommentIndicator = xlCommentIndicatorOnly 

With Application 
    .ScreenUpdating = True 
    .Calculation = lngCalc 
    .DisplayAlerts = True 
End With 

End Sub