VBA代码优化:摆脱For循环,加速数组查找
VBA代码优化:摆脱For循环,加速数组查找
在VBA中处理大型数组时,使用双重循环进行查找效率极低。想要提升代码运行速度?试试以下优化方案:
1. 使用 Application.Match 函数
Application.Match 函数可以在数组中快速匹配数据,完美替代双重循环。vbaDim dataArr() As Variant' 假设 dataArr 是一个二维数组
Dim searchValue As VariantsearchValue = 123
Dim i As Long, j As LongDim numRows As Long, numCols As LongnumRows = UBound(dataArr, 1)numCols = UBound(dataArr, 2)
' 遍历数组的每一列,使用 Match 函数查找匹配的行索引For j = LBound(dataArr, 2) To UBound(dataArr, 2) Dim matchIndex As Variant matchIndex = Application.Match(searchValue, Application.Index(dataArr, 0, j), 0) If Not IsError(matchIndex) Then ' 找到匹配的值 i = CLng(matchIndex) Debug.Print '找到匹配的值在数组中的位置:行 ' & i & ',列 ' & j ' 进行其他操作 ' ... End IfNext j
2. 使用 Application.WorksheetFunction.Index 函数
Application.WorksheetFunction.Index 函数可以二维数组中精确定位目标数据。vbaDim dataArr() As Variant' 假设 dataArr 是一个二维数组
Dim searchValue As VariantsearchValue = 123
Dim i As Long, j As LongDim numRows As Long, numCols As LongnumRows = UBound(dataArr, 1)numCols = UBound(dataArr, 2)
' 使用 Index 函数查找匹配的位置Dim matchResult As VariantmatchResult = Application.WorksheetFunction.Index(dataArr, _ Application.WorksheetFunction.Match(searchValue, Application.Index(dataArr, 0, 1), 0), _ Application.WorksheetFunction.Match(searchValue, Application.Index(dataArr, 1, 0), 0))
If Not IsError(matchResult) Then ' 找到匹配的值 i = matchResult.Row j = matchResult.Column Debug.Print '找到匹配的值在数组中的位置:行 ' & i & ',列 ' & j ' 进行其他操作 ' ...End If
3. 字典数据结构
将数据加载到字典数据结构,利用其强大的查找功能快速匹配目标值。vbaDim dataArr() As Variant' 假设 dataArr 是一个二维数组
Dim searchValue As VariantsearchValue = 123
Dim dict As ObjectSet dict = CreateObject('Scripting.Dictionary')
Dim i As Long, j As LongDim numRows As Long, numCols As LongnumRows = UBound(dataArr, 1)numCols = UBound(dataArr, 2)
' 将数据加载到字典中For i = LBound(dataArr, 1) To UBound(dataArr, 1) For j = LBound(dataArr, 2) To UBound(dataArr, 2) dict(dataArr(i, j)) = Application.Index(dataArr, i, j) Next jNext i
' 使用字典查找匹配的值If dict.Exists(searchValue) Then ' 找到匹配的值 Dim matchResult As Variant matchResult = dict(searchValue) i = matchResult.Row j = matchResult.Column Debug.Print '找到匹配的值在数组中的位置:行 ' & i & ',列 ' & j ' 进行其他操作 ' ...End If
选择合适的优化方案,助你告别蜗牛速度,享受代码飞速运行的快感!如有疑问,欢迎随时交流。
原文地址: https://www.cveoy.top/t/topic/bUuX 著作权归作者所有。请勿转载和采集!