2013-11-21 115 views
-1

美好的一天先生! 我可以問一個關於如何/將使用什麼代碼在vba中同時搜索兩個值的問題?例如,如果在同一行中找到值「4AC」和日期「04/11/2013」​​,我想設置一個條件,該條件將變爲「真」。 感謝提前和更多的權力!如何在VBA中連續查找兩個值excel

+0

這將是巨大的做,包括你已經嘗試過什麼,結果。代碼是否工作或者您是否遇到錯誤? – L42

回答

1

使用Excel的Range.Find函數,如下所示,在此IsFound函數中進行檢查。

Function IsFound(ByVal rngRowToSearch As Range, strSearchTerm1 as String, strSearchTerm2 As String) As Boolean 

    Dim rngFind1 as Range, rngFind2 as Range 

    ' try to find 1st value. If it exists, rngFind1 range will have the address. Else Nothing 
    rngFind1 = rngRowToSearch.EntireRow.Find(What:=strSearchTerm1, LookIn:=xlValues, MatchCase:=False) 

    ' try to find 2nd value. If it exists, rngFind1 range will have the address. Else Nothing 
    rngFind2 = rngRowToSearch.EntireRow.Find(What:=strSearchTerm2, LookIn:=xlValues, MatchCase:=False) 

    IsFound = Not (rngFind1 Is Nothing Or rngFind2 Is Nothing) 

End Function 

此外,您將調用IsFound功能如下。

Dim blnFound as Boolean 
blnFound = IsFound(Activesheet.Range("A1"),"4AC","04/11/2013") 

然後做任何你想用blnFound

+0

IF塊可以簡化爲一行:'blnFound = Not(rngFind1是Nothing或rngFind2是Nothing)'。改變它作爲輸入功能與行是一個好主意! – PatricK

+0

@PatricK感謝重構推薦。自從我寫VBA以來已經有十年了,很顯然有一些代碼「生鏽」。我現在更新了代碼,請再次檢查代碼:) – Shiva

+0

看起來不錯! @ user3015762你可以檢查這是否適合你的需要?如果是,請標記爲答案。 – PatricK