我正在嘗試在範圍內查找關鍵字(例如數量,數量,數量,...等)(但在此範圍內),但我遇到問題;搜索是緩慢的,因爲我使用InStr
和For each cell in UsedRange
在UsedRange中查找關鍵字 - VBA(Excel)
方法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
怎麼可能是錯的?
它的工作,謝謝。我會盡力檢查我做錯了什麼。 – Tima
(@Tima - 如果這對你有效,可以通過點擊帖子左邊的複選標記,在上/下箭頭下面標記爲答案。) – BruceWayne
'Dim QtyWord(5)As String''' Dim QtyWord (4)As String' - 如果不打算使用索引5,則沒有必要爲索引5分配一個位置。而且,如果搜索'xlPart',如果沒有找到''Qty''',或者搜索''Qnty'',如果沒有找到''Qty''',沒有找到''Qty''的位置。 。 – YowE3K