如何解决Excel VBA-每次执行后宏指令执行时间变慢
我有一个如下代码:
-
刷新大约10.000行的查询。
-
根据某些条件将数据拆分为各种2D阵列(我总共有十几个不同的2D阵列)。
-
将每个2D阵列粘贴到不同的工作表中。
当我第一次运行宏时,大约需要18秒,第二次运行时是30秒,第三次运行时是35秒,第四次运行是45秒,依此类推。每次运行时,查询中的数据都是完全相同的(它不会频繁更改,或者最多只能更改一两行)。
如果我不知道某些内存问题,有人可以向我解释吗?我还尝试将矩阵粘贴到图纸上后等于Nothing的值,但这并没有改变每次运行的速度。任何帮助将不胜感激。
P.S。代码很长,我觉得将所有内容都粘贴到这里是没有用的。它的工作原理大致如下:
Sub GetMatrix()
Dim Matrix As Variant,IndexMatrix As Long,i As Long,NoRows As Long
IndexMatrix = 0
ReDim Matrix(IndexMatrix,2)
NoRows = Application.CountA(Range("A:A"))
For i = 2 To NoRows
If Cells(i,1) = "Something" Then
Matrix(IndexMatrix,0) = "Something"
Matrix(IndexMatrix,1) = "Something"
Matrix(IndexMatrix,2) = "Something"
IndexMatrix = IndexMatrix + 1
ReDim Preserve Matrix(IndexMatrix,2)
End If
Next
GetMatrix = Matrix
End Sub
解决方法
请尝试下一个适应功能,
Function GetMatrix() As Variant
Dim sh As Worksheet,arr As Variant,Matrix As Variant
Dim IndexMatrix As Long,i As Long,LastRow As Long
Set sh = ActiveSheet
LastRow = sh.Range("A" & Rows.count).End(xlUp).Row
arr = sh.Range("A1:A" & LastRow).Value
ReDim Matrix(2,UBound(arr)) 'to admit redim preserve (only on the last dimension) at the end
For i = 2 To LastRow
If arr(i,1) = "Something" Then
Matrix(0,IndexMatrix) = "Something"
Matrix(1,IndexMatrix) = "Something"
Matrix(2,IndexMatrix) = "Something"
IndexMatrix = IndexMatrix + 1
End If
Next
ReDim Preserve Matrix(2,IndexMatrix - 1)
GetMatrix = Matrix
End Function
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。