我不確定你在哪裏坐在這個解決方案上,因爲它聽起來像問題已經隨着時間的推移而演變。根據我所理解的問題,您希望找到列A中與您的搜索詞匹配的所有行,然後僅搜索列B中的那些行以獲取不同的搜索詞。因此,舉例來說:
A B
Apple Cobbler
Cherry Cobbler
Peach Pie
Apple Pie
Apple iPad
如果2個檢索詞是「蘋果」和「派」,它會返回第4行
我將與集合對象做到這一點。
Dim myCol As New Collection
Dim r As Integer
Dim FirstSearchTerm As String
Dim SecondSearchTerm As String
For r = 1 To Sheet1.UsedRange.Rows.Count
If Sheet1.Cells(r, 1) = FirstSearchTerm Then
myCol.Add r, Sheet1.Cells(r, 2)
End If
Next
MsgBox myCol.Item(SecondSearchTerm) 'Returns 4
當然,這也預示着蘋果派不會出現兩次。例如:
A B
Apple Cobbler
Cherry Cobbler
Peach Pie
Apple Pie
Apple iPad
Apple Pie
將打破此代碼。
編輯:迴應評論
所以,現在你要搜索這樣的事情?
A B C D
Apple Cobbler Joe Blow
Cherry Cobbler Joe DiMaggio
Peach Pie Sally Sparrow
Apple Pie Jane Goodall
Apple iPad Ivan Terrible
Apple Pie Sally Sparrow
Apple Pie Jane Seymour
並能夠當你有4個獨立的搜索詞「蘋果」,「丿」,「簡」和「古道爾」返回一行4?
此時您可能想考慮重構您的數據! J/K:D
因此,我們不是將單元格的值添加到Collection對象,而是將一行添加到Collection對象。然後,我們必須繼續循環播放我們的收藏集,直到我們擁有漢蘭達人(可以只有一個!)本質上,我們繼續雜耍回來和第四次篩選出壞數據,直到我們只剩下物品。我相信有一種方法可以遞歸地做到這一點,但它的5點。
Dim myFirstCol As New Collection
Dim mySecCol As New Collection
Dim x As Integer 'Switching to x so its not as confusing
Dim FirstSearchTerm As String
Dim SecondSearchTerm As String
Dim ThirdTerm As String
Dim FourthTerm As String
FirstSearchTerm = "Apple"
SecondSearchTerm = "Pie"
ThirdTerm = "Jane"
FourthTerm = "Seymour"
'First, get all rows matching our first term
For x = 1 To Sheet1.UsedRange.Rows.Count
If Sheet1.Cells(x, 1) = FirstSearchTerm Then
myFirstCol.Add x 'Just save the row number
End If
Next
'now loop through that collection search for our second term
'Item(x) contains the row number for rows that matched our search terms
For x = 1 To myFirstCol.Count
If Sheet1.Cells(myFirstCol.Item(x), 2) = SecondSearchTerm Then
mySecCol.Add myFirstCol.Item(x)
End If
Next
'And loop through again for the 3rd term
Set myFirstCol = New Collection 'Reuse it
For x = 1 To mySecCol.Count
If Sheet1.Cells(mySecCol.Item(x), 3) = ThirdTerm Then
myFirstCol.Add mySecCol.Item(x)
End If
Next
'And fourth
Set mySecCol = New Collection 'Reuse it
For x = 1 To myFirstCol.Count
If Sheet1.Cells(myFirstCol.Item(x), 4) = FourthTerm Then
mySecCol.Add myFirstCol.Item(x)
End If
Next
msgbox mySecCol.Item(1) 'Which is the row number matching all our terms
來源
2015-07-21 18:51:27
Tim
這是一個很好的問題,但答案並不明顯。我建議你閱讀這篇文章:http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/ 我有一個稍微不同的版本,強烈啓發了我可以給你的錫德,但我不確定我是否理解你的問題的第一句話。如果你澄清它會有所幫助! (關於您要搜索的順序) –
@DavidGM鏈接幫助巨大。我已經對我的代碼進行了相應的更改,但是我現在被其他東西卡住了。通過直接信息與你聯繫會更容易,還是我應該在這裏重新編輯我的帖子? – user3242614
重新編輯,也許別人可以幫助你!除非它沒有聯繫,否則提出一個新問題。 –