標題:
如何改善這段程式,讓執行效率提升?
[打印本頁]
作者:
av8d
時間:
2015-4-21 19:16
標題:
如何改善這段程式,讓執行效率提升?
Sub test()
'年度分析,開銷前3名
Application.ScreenUpdating = False
W = [W]
r = [A1].CurrentRegion.Rows.Count
Range("B7:M" & r).ClearContents
Range("B2:M3").ClearContents
myyear = [A1].Value
For c = 2 To 13
mymonth = myyear & "/" & Trim(Cells(1, c).Value)
income = 0
expense = 0
pay = 0
v = 11
With Sheets("DataCopy")
er = .[A100000].End(3).Row
For r = 2 To er
If myyear & "/" & Format(.Cells(r, 1).Value, "m月份") = mymonth Then
money = Val(.Cells(r, 3).Value)
Select Case .Cells(r, 2).Value
Case "收入": income = income + money
Case "支出": expense = expense + money
Case "分期付款": expense = expense + money: pay = pay + 1
End Select
myitem = .Cells(r, 4).Value
If .Cells(r, 2).Value <> "收入" Then
Set cell = Columns(c + 1).Find(myitem)
If Not cell Is Nothing Then
cell.Offset(, -1).Value = cell.Offset(, -1).Value + money
Else
Cells(v, c).Value = money
Cells(v, c + 1).Value = .Cells(r, 4).Value
v = v + 1
End If
End If
End If
Next r
If Cells(11, c) <> "" Then
Set rng = Range(Cells(11, c), Cells(v - 1, c + 1))
rng.Sort key1:=Cells(11, c), order1:=xlDescending
X = 0
v = 11
Do Until Cells(v, c).Value = ""
If InStr(W, Cells(v, c + 1)) = 0 Then
If X < 3 Then
X = X + 1
Cells(X + 6, c).Value = X & ". " & Cells(v, c + 1).Value & " / " & Cells(v, c).Value & "元"
End If
End If
Cells(v, c).Value = v - 10 & ". " & Cells(v, c + 1).Value & " / " & Cells(v, c).Value & "元"
Cells(v, c + 1).Value = ""
v = v + 1
Loop
End If
End With
Cells(2, c).Value = IIf(income <> 0, income, "")
Cells(3, c).Value = IIf(expense <> 0, expense, "")
Cells(10, c).Value = pay
Next c
Application.ScreenUpdating = True
'自動換行
Rows("7:100000").EntireRow.AutoFit
Application.ScreenUpdating = True
End Sub
複製代碼
以上是某位老師撰寫,有點忘了是誰(失禮了),原本都用XP的Excel執行,效率都還OK,
換成2010後,執行以後會變得非常非常的慢,不知道有沒有辦法改善,謝謝!
作者:
PKKO
時間:
2015-4-21 20:01
回復
1#
av8d
流程的部分我沒有分析,但我確定的是可以用陣列會執行的更快
因為陣列的運作速度會比讀取CELLS快N倍
在開頭的地方先
AR=[a1].currentregion'此行風險在於中斷的儲存格,若有中斷的儲存格請用下方
AR=[a1].resize(x,y)'可自訂陣列大小
之後AR(1,1) 就會等於 cells(1,1)=>因此將程式碼取代即可, 而.value的部分則可刪除
with 的部分一樣用AR2=.[a1].currentregion'即可,AR2(1,1)=.cells(1,1)
但後面sort的部分要保留原本的CELLS才不會有問題
以及最後輸出的.cells.value因為要輸出,當然不可取代為陣列
歡迎光臨 麻辣家族討論版版 (http://forum.twbts.com/)