search所有匹配string的工作簿

我正在尝试编写一个vba脚本,它将search多页工作簿并返回所有包含dataToFindstring的结果。 目前,我正忙于find和findNext函数……下面的代码似乎是按照我想要的方式查看所有的页面,但它只是返回一个单一的结果。

以下是我的代码。

Function searchGrids(contract As String, pbp As String, county As String) As String() Dim datatoFind As String Dim sheetCount As Integer Dim counter As Integer Dim currentSheet As Integer Dim pos As Integer Dim endFlag As Integer endFlag = 0 Set indGrid = Workbooks("2014NumberGrid") On Error Resume Next currentSheet = ActiveSheet.Index datatoFind = contract & "-" & pbp sheetCount = indGrid.Sheets.Count For counter = 1 To sheetCount indGrid.Sheets(counter).Activate If IsError(Cells.find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False).Activate) = False Then Exit For Next counter pos = InStr(ActiveCell.Value, datatoFind) If pos > 0 Then MsgBox (ActiveCell.EntireRow.Cells(1, 2).Value) End If Do While endFlag = 0 If pos = 0 Then endFlag = 1 Else For counter = 1 To sheetCount Do While pos > 0 indGrid.Sheets(counter).Activate indGrid.FindNext(ActiveCell).Activate pos = InStr(ActiveCell.Value, datatoFind) MsgBox (ActiveCell.EntireRow.Cells(1, 2).Value) Loop Next counter End If Loop Sheets(currentSheet).Activate End Function 

谢谢

PS有人问函数应该返回什么值。 目前,这并不重要。 我所要做的就是访问电子表格的数据,以便我可以玩弄它。 然后,我将返回一个在函数内部构build的复杂string或一个string数组。 任何返回的variables将从其他工作簿中find的数据构build。 如果有一个更好的方法(比如说,返回所有行的范围内的所有行),那么我当然绝对是开放的。

这里是你可能适应的一个 。 小组通过所有的工作表寻找单词快乐

对于find的每个实例,loggingfind的行的A列中的工作表名称,地址和值。 信息然后输出:

 Sub FindingData() Dim sh As Worksheet, v As String, r As Range, _ msg As String v = "happy" For Each sh In Worksheets With sh For Each r In .UsedRange If InStr(1, r.Value, v) > 0 Then msg = msg & .Name & vbTab & r.Address & vbTab & CStr(r.EntireRow.Cells(1).Value) & vbCrLf End If Next r End With Next sh MsgBox msg End Sub 

注意:我正在使用循环而不是.FIND()方法。