2014-07-17 28 views
0

我正在尝试编写一个vba脚本,它将搜索多页工作簿并返回包含dataToFind字符串的所有结果。目前,我正忙于使用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 

感谢

附:有人问函数应该返回什么样的价值。目前,这并不重要。我所要做的就是访问电子表格的数据,以便我可以玩弄它。然后我将返回一个在函数内部构建的复杂字符串或一个字符串数组。任何返回的变量都将从其他工作簿中找到的数据构建。如果有更好的方法(比如说,返回所有具有内部词的行的范围),那么我当然完全开放。

+0

该函数应该返回什么值? –

+0

请参阅上面的修改。 –

回答

2

这是您可能适应的sub。子看起来直通所有工作表中列中找到行的记录搜索单词快乐

对于每个实例中发现,工作表的名称,地址,和值。该信息然后输出:

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()方法。

相关问题