I am trying to look for a Keyword (eg Quantity, Qty, Qty., ... , etc) within range (in this case used range) but I am experiencing a problem; the search is slow because I am using InStr
and For each cell in UsedRange
Method 1 (Slow):
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
Method 2 (Not working): No match found
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
What could possibly be wrong ?
For your second one, you have a few issues. First, you've spelled the function name incorrectly when assigning it the result of Find
. Then, you'll need to use xlPart
for your LookAt
argument when looking for a match within a string. Then, you'll need to exit the function, once a match has been found. Also, you'll need to precede the argument's name with the keyword Optional
so that the argument can be made optional. Try the following...
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
Note that both the size of the array QtyWord
and the number of search terms have been adjusted, as per YowE3K
's comments.
you could also use this form of the loop (part of the loop code not shown in this snippet)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.