我已經形成了代碼做的問題是試圖得到它找到多個結果的搜索。目前它將返回每個選項卡上字符串的第一個位置,但隨後繼續。當我實現While循環當前註釋掉它似乎找到第一個結果,然後轉義循環。VBA在Excel中搜索字符串在多個選項卡,並返回地點
我不知道是否有一個古怪的VBA循環,我失蹤或我雖然檢查是不是很正確,但我試圖通過分解調試和使用消息框,但除了縮小之外無濟於事我相信問題在while循環代碼中。
Public Function GetSearchArray(strSearch As String) As String
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress As Range
For Each SHT In ThisWorkbook.Worksheets
'MsgBox "Looping over worksheets"
Set rFND = Nothing
With SHT.UsedRange
'MsgBox "Searching for" & strSearch
Set rFND = .Cells.Find(What:="*" & strSearch & "*", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
'Save first result so we can exit the loop
If sFirstAddress Is Nothing Then
MsgBox "We have a result and sFirstAddress is nothing"
Set sFirstAddress = rFND
End If
'Need to loop within the sheet to keep finding results
'While (Not rFND Is Nothing) And rFND <> sFirstAddress
'Deal with the results and build a string
If strResults = "" Then
'MsgBox "No prev results"
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
MsgBox "First result " & strResults
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
MsgBox strResults
End If
Set rFND = .FindNext(rFND)
'Wend
End If
End With
MsgBox "End sheet loop.."
Next
MsgBox "Finished going over sheets"
MsgBox strResults
End Function
這與我想要的完全一樣。一個擴展 - 我將如何從單元中調用它並將輸出返回到單元格中?我試過第二個函數調用你的重寫,但它不工作。 – mhollander38
在一個單元格:'= GetSearchArray(「測試」)'如果你想要的結果要以比其他的東西分隔「|」,你可以使用Substitue,如:'=替換(GetSearchArray(「測試」),「| 「,」,「)' – tigeravatar
嗯我試過,但單元格只是錯誤和顯示#VALUE! – mhollander38