excel vba词典vlookup

我的代码需要超过一个小时才能完成3500行,但我需要为超过40000行数据工作。

我正在寻找替代我的代码,通过使用字典,在感兴趣的上下文中提高性能。

任何人都可以帮我吗?

Sub StripRow2Node() 'Read the Strip Design table With Sheets("Design-Moment") Sheets("Design-Moment").Activate LastR1 = .Range("B" & Cells.Rows.Count).End(xlUp).Row DM_arr = .Range(Cells(1, 1), Cells(LastR1, 7)) 'Col 1 to Col 7 DM_count = UBound(DM_arr, 1) End With 'Read the x and y coordinations and thickness of a node in node design With Sheets("Design-Shear") Sheets("Design-Shear").Activate LastR2 = .Range("B" & Cells.Rows.Count).End(xlUp).Row DS_arr = .Range(Cells(1, 4), Cells(LastR2, 5)) 'Col 4 to Col 5 SX_arr = .Range(Cells(1, 26), Cells(LastR2, 27)) SY_arr = .Range(Cells(1, 30), Cells(LastR2, 31)) DS_count = UBound(DS_arr, 1) End With '** Find correponding reference row in Design-Moment for nodes** 'Match node to striip station and output row index For i = 5 To DS_count XStrip = SX_arr(i, 1) XStation = DS_arr(i, 1) YStrip = SY_arr(i, 1) YStation = DS_arr(i, 2) For j = 5 To DM_count If DM_arr(j, 1) = XStrip Then 'X-Strip Name is matched If DM_arr(j, 4) >= XStation And DM_arr(j - 1, 4) < XStation Then SX_arr(i, 2) = j 'matched row reference for X-strip End If End If If DM_arr(j, 1) = YStrip Then If DM_arr(j, 5) <= YStation And DM_arr(j - 1, 5) > YStation Then SY_arr(i, 2) = j End If End If Next j Next i 'Write the matched strip information to node For i = 5 To LastR2 With Sheets("Design-Shear") .Cells(i, 27) = SX_arr(i, 2) .Cells(i, 31) = SY_arr(i, 2) End With Next i 

结束小组

我怀疑几乎所有的时间都是用单元格写到这里的表格中的:

 'Write the matched strip information to node For i = 5 To LastR2 With Sheets("Design-Shear") .Cells(i, 27) = SX_arr(i, 2) .Cells(i, 31) = SY_arr(i, 2) End With Next i 

写回Excel比从Excel读取要慢得多。 我build议closures屏幕更新和计算,在单独的数组中累积结果(当前是X_arr(i,2)和SY_arr(i,2)),然后将数组写回单个操作的范围,而不是单元格-细胞

有几点需要改进:
1.使用合格的引用来避免.activate语句
你开始很好

 With Sheets("Design-Shear") ... DS_arr = .Range(Cells(1, 4), Cells(LastR2, 5)) 'Col 4 to Col 5 

但是无法使Cells对象引用With块。 反而使用

 With Sheets("Design-Shear") ... DS_arr = .Range(.Cells(1, 4), .Cells(LastR2, 5)) 'Col 4 to Col 5 

现在你不必再激活工作表了。

  1. 从代码中,我必须假设在这个语句中只有一个可能的匹配返回:

    SX_arr(i, 2) = j

i 否则,第二,第三…出现会覆盖j这个值。 如果确实如此,一旦发现匹配,就可以停止循环j

 SX_arr(i, 2) = j 'matched row reference for X-strip Exit For 

两个快捷方式如果DM_arr(j, 1)可以匹配XStripYStrip 。 如果这些匹配是互斥的,则使用ElseIf而不是If作为第二个语句。
快捷的j loop应该会显着改善运行时间。 当然,如果你需要最后的匹配索引(而不是第一个 ),那么这将不适用。

编辑:
对于字典解决scheme,请参阅Jeeped的优秀代码: https ://codereview.stackexchange.com/questions/133664/searching-values-of-range-x-in-range-y