【发布时间】:2022-01-12 22:08:27
【问题描述】:
example2 example1 The file name I'm trying to match is on Row A and I'm looking through Row I to see if there is a match 我找到了这段代码,我不记得在哪里,但我试图将一行零件号与其图像文件名的一行匹配。这段代码有效,但是,当我运行它时存在一个问题,即使只计算 1 列也需要很长时间,当我一次执行数百个时,我的 excel 只是停止响应,并且我需要匹配数千种产品。我对 VBA 很陌生,所以我什至无法找出问题所在。
请帮忙,谢谢。
'Name function and arguments
Function SearchChars(lookup_value As String, tbl_array As Range) As String
'Declare variables and types
Dim i As Integer, str As String, Value As String
Dim a As Integer, b As Integer, cell As Variant
'Iterste through each cell
For Each cell In tbl_array
'Save cell value to variable
str = cell
'Iterate through characters
For i = 1 To Len(lookup_value)
'Same character?
If InStr(cell, Mid(lookup_value, i, 1)) > 0 Then
'Add 1 to number in array
a = a + 1
'Remove evaluated character from cell and contine with remaning characters
cell = Mid(cell, 1, InStr(cell, Mid(lookup_value, i, 1)) - 1) & Mid(cell, InStr(cell, Mid(lookup_value, i, 1)) + 1, 9999)
End If
'Next character
Next i
a = a - Len(cell)
'Save value if there are more matching characters than before
If a > b Then
b = a
Value = str
End If
a = 0
Next cell
'Return value with the most matching characters
SearchChars = Value
End Function
【问题讨论】:
-
For Each cell In tbl_array- 这是逐个单元格的迭代,非常慢。相反,您想将tbl_array.Value读入Variant数组,然后循环该数组。换句话说,你认为你有一个数组,但实际上你没有。 -
您好,感谢您的回复。那么我是否将 tbl_array 中的每个单元格更改为 tbl_array.Value 中的每个单元格?抱歉,我真的不知道自己在做什么。
-
或许先阅读Arrays and Ranges。
-
尝试将 Excel 从自动计算切换到手动:文件->选项->公式。更新每个单元格后,Excel 可能会重新计算整个工作簿。如果将其设置为手动,则可以在脚本运行完成后按 F9 手动重新计算。这可能无法完全解决问题,但可能会产生很大的不同
-
@ANeonTetra 感谢您的帮助!
标签: excel vba user-defined-functions