在UsedRange中查找关键字 – VBA(Excel)

我正在尝试寻找一个关键字(如数量,数量,数量,…等)范围内(在这种情况下使用范围),但我遇到一个问题; search速度很慢,因为我正在使用InStrFor each cell in UsedRange

方法1(慢):

 Private Function GetQtyColFromBOQ(thisBOQ As Worksheet) As Range Dim QtyWord(5), QtyWordG, Delim As String Dim cl As Range If thisBOQ Is Nothing Then Set thisBOQ = ActiveSheet Delim = "|#|" QtyWord(0) = "Quantity" QtyWord(1) = "Qty" QtyWord(2) = "Qty." QtyWord(3) = "Qnty" QtyWord(4) = "Qnty." QtyWordG = Delim & Join(QtyWord, Delim) For Each cl In thisBOQ.UsedRange If InStr(1, QtyWordG, Delim & cl.Value & Delim, vbTextCompare) Then Set GetQtyColumnFromBOQ = cl ' function return Exit For End If Next End Function 

方法2(不工作):找不到匹配

 Private Function GetQtyColFromBOQ(thisBOQ As Worksheet) As Range Dim QtyWord(5) As String If thisBOQ Is Nothing Then Set thisBOQ = ActiveSheet QtyWord(0) = "Quantity" QtyWord(1) = "Qty" QtyWord(2) = "Qty." QtyWord(3) = "Qnty" QtyWord(4) = "Qnty." Dim i As Integer For i = 0 To 4 Set GetQtyColumnFromBOQ = thisBOQ.UsedRange.Find(QtyWord(i), LookAt:=xlWhole) Next i End Function 

有什么可能是错的?

对于你的第二个,你有几个问题。 首先,在为其分配Find结果时,错误地拼写了函数名称。 然后,在查找string内的匹配项时,需要使用xlPart作为LookAt参数。 然后,一旦find匹配项,就需要退出该function。 此外,您需要在参数的名称前面加上关键字“ Optional ,以使参数成为可选参数。 试试以下…

 Private Function GetQtyColFromBOQ(Optional thisBOQ As Worksheet) As Range Dim QtyWord(2) As String If thisBOQ Is Nothing Then Set thisBOQ = ActiveSheet QtyWord(0) = "Quantity" QtyWord(1) = "Qty" QtyWord(2) = "Qnty" Dim i As Integer For i = LBound(QtyWord) To UBound(QtyWord) Set GetQtyColFromBOQ = thisBOQ.UsedRange.Find(QtyWord(i), LookAt:=xlPart, MatchCase:=False) If Not GetQtyColFromBOQ Is Nothing Then Exit Function End If Next i Set GetQtyColFromBOQ = Nothing End Function 

请注意,根据YowE3K的评论,数组QtyWord的大小和search项的数量都已经被调整过了。

你也可以使用这种forms的循环(循环代码的一部分在这个片段中没有显示)

 Dim wrd As Variant For Each wrd In Array("Quantity", "Qty", "Qty.", "Qnty", "Qnty.") Set GetQtyColFromBOQ = thisBOQ.UsedRange.Find(wrd, LookAt:=xlPart, MatchCase:=False) . . Next wrd