提升效率
公式(暫無)
VBA
With xSheet.Range(myRange)
' select range
Set c = .Find("My Key Word") ', LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
do
lineno2 = c.Row() ' get row number
.... ' process business logic
'Find next line
Set c = .FindNext(c)
If c Is Nothing Then Exit Do
Loop While c.Address <> firstAddress
End if
End With
2:寫入
Dim myRange As Range
Dim strResultArray(1 to 1000, 1 to 13) as String ' saved result from input to write out
Set myRange = rSheet.Range("A1:M1000")
myRange = strResultArray
Set myRange = Nothing
3:盡量使用VBA原有的屬性、方法和WORKSHEET函數(shù)
求平均工資的例子:
for each c in worksheet(1).range(“a1:a100”)
totalvalue=totalvalue+c.value
next
averagevalue=totalvalue/worksheet(1).range(“a1:a1000”).rows.count
而下面的代碼程序比上面的例子快得多
averagevalue=application.worksheetfunction.average(worksheets(1).range(“a1:a1000”))
4:盡量減少使用對象引用,尤其在循環(huán)中
1、使用With語句
例:workbooks(1).sheets(1).range(“a1:a1000”).font.name=”pay”
workbooks(1).sheets(1).range(“a1:a1000”).font.fontstyle=”bold”
而下面的代碼程序比上面的例子快得多
With workbooks(1).sheets(1).range(“a1:a1000”).font
.name=”pay”
.fontstyle=”bold”
end with
2、使用對象變量。
如果你發(fā)現(xiàn)一個對象引用被多次使用,則你可以將此對象用SET設(shè)置為對象變量,以減少對對象的訪問。如:
workbooks(1).sheets(1).range(“a1”).value=100
workbooks(1).sheets(1).range(“a2”).value=200
而下面的代碼程序比上面的例子快得多
Set mysheet=workbooks(1).sheets(1)
Mysheet. range(“a1”).value=100
Mysheet.range(“a2”).value=200
3、在循環(huán)中要盡量減少對象的訪問。
For k=1 to 1000
Sheets(“sheet1”).select
Cells(k,1).value=cells(1,1).value
Next k
Set thevalue =cells(1,1).value
Sheets(“sheet1”).select
For k=1 to 1000
Cells(k,1).value=thevalue
Next k
5:減少對象的激活和選擇
如果你是通過錄制宏學(xué)習(xí)VBA的,則你的程式序里一一充滿了對象的激活和選擇,如WORKSHEETS(XXX).ACTIVATE、Sheets(XXX).select等.但事實上大多數(shù)的情況下這些操作是不必須的.例如:
sheets(“sheet3”).select
range(“a1”).value=100
range(“a2”).value=200
可改為
with sheets(“sheet3”)
.range(“a1”).value=100
.range(“a2”).value=200
end with
6:關(guān)閉屏幕更新
如果前面三條做的比較差,則關(guān)閉屏幕更新是提高VBA程序運行速度的最有效方法,縮短運行時間2/3左右。關(guān)閉屏幕更新的方法:
Application.screenupdate=false
請不要忘記VBA程序運行結(jié)束時再將該值設(shè)回來
Application.screenupdate=true
posted on 2015-10-09 11:48 小辭猬 閱讀(164) 評論(0) 編輯 收藏 所屬分類: VBA