【发布时间】:2020-12-02 04:57:42
【问题描述】:
我创建了一个查找函数,该函数从同一个工作表中的一个单独选项卡中查找结果,其中有 4 个不同的字段要匹配。
运行时,这完全需要很长时间才能完成(到我必须终止宏运行的地步)。我需要基于完全相同的匹配标准为 8 个不同的字段构建相同的查找函数。有关如何加快此查询或以更动态的方式构建它的任何建议,以便我可以一次查找所有 8 列,而不是为每个查找字段构建函数和子项?
Function fcst_bal_find(ByVal Anode As String, ByVal LoB As String, ByVal Month As String, ByVal Year As String) As Variant
Dim Fcst_Essbase As Worksheet
Dim fcst_rowcnt
Dim act_rowcnt
fcst_rowcnt = Sheets("Date Dims").Range("B7")
act_rowcnt = Sheets("Date Dims").Range("B8")
Set Fcst_Essbase = Sheets("Fcst Essbase Pull")
For i = 2 To fcst_rowcnt + 4
If WorksheetFunction.Trim(Fcst_Essbase.Cells(i, 1).Value) = Anode Then
If WorksheetFunction.Trim(Fcst_Essbase.Cells(i, 2).Value) = LoB Then
If WorksheetFunction.Trim(Fcst_Essbase.Cells(i, 3).Value) = Month Then
If "Y" & Right(WorksheetFunction.Trim(Fcst_Essbase.Cells(i, 4).Value), 2) = Year Then
fcst_bal_find = Fcst_Essbase.Cells(i, 5).Value
Exit Function
End If
End If
End If
End If
Next i
fcst_bal_find = "N/A"
End Function
Sub balfcst_find()
Dim fcst_tab As Worksheet
Dim match As Variant
Dim Anode As String
Dim LoB As String
Dim Month As String
Dim Year As String
Dim fcst_rowcnt
Dim act_rowcnt
fcst_rowcnt = Sheets("Date Dims").Range("B7")
act_rowcnt = Sheets("Date Dims").Range("B8")
Set fcst_tab = Sheets("Cartesian Product - Fcst")
For i = 2 To fcst_rowcnt
Anode = fcst_tab.Range("A" & i).Value
LoB = fcst_tab.Range("B" & i).Value
Month = fcst_tab.Range("C" & i).Value
Year = fcst_tab.Range("D" & i).Value
match = fcst_bal_find(Anode, LoB, Month, Year)
fcst_tab.Cells(i, 5) = match ' test the output
Next i
End Sub
【问题讨论】:
-
使用 Variant 数组 - read the range in question into an array,并循环数组,而不是像现在这样循环单元格。
-
好的。查找数据最快的是自动过滤器,其次是字典。您是否也尝试过是的 bigbens 评论 - 循环遍历数组作为单元格的对立面。它也会更快。
-
根据我的经验,'AutoFilter` 不是禁食@DavidWooley-AST。它很慢,甚至可能是错误的。变体数组是要走的路。
-
好的。我同意 。我正在经历一些 VBA YouTubers 的时代,一个爱尔兰人。 “Excel 宏掌握”。取决于什么过程和目的。但我总是喜欢挑战自己..
-
@David Wooley - AST:你可能指的是Advanced Filter,而你说的是来自Excel Macro Mastery的Paul Kelly。
标签: excel vba performance