2017-07-16 753 views
0

我正在嘗試在範圍內查找關鍵字(例如數量,數量,數量,...等)(但在此範圍內),但我遇到問題;搜索是緩慢的,因爲我使用InStrFor 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 

怎麼可能是錯的?

回答

4

對於你的第二個問題,你有幾個問題。首先,在爲其分配Find的結果時,錯誤地拼寫了函數名稱。然後,當在字符串中查找匹配項時,您需要使用xlPart作爲參數LookAt。然後,一旦找到匹配項,就需要退出該功能。另外,您需要在參數名稱前面加上關鍵字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 

注意,陣列QtyWord和搜索字詞的數量無論是大小進行了調整,按照YowE3K的意見。

+0

它的工作,謝謝。我會盡力檢查我做錯了什麼。 – Tima

+0

(@Tima - 如果這對你有效,可以通過點擊帖子左邊的複選標記,在上/下箭頭下面標記爲答案。) – BruceWayne

+0

'Dim QtyWord(5)As String''' Dim QtyWord (4)As String' - 如果不打算使用索引5,則沒有必要爲索引5分配一個位置。而且,如果搜索'xlPart',如果沒有找到''Qty''',或者搜索''Qnty'',如果沒有找到''Qty''',沒有找到''Qty''的位置。 。 – YowE3K

1

你也可以使用這種形式的循環的(在這個片段中未顯示的循環代碼的一部分)

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