Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 在工作簿中搜索字符串的所有匹配项_Excel_Vba_Search - Fatal编程技术网

Excel 在工作簿中搜索字符串的所有匹配项

Excel 在工作簿中搜索字符串的所有匹配项,excel,vba,search,Excel,Vba,Search,我正在尝试编写一个vba脚本,它将搜索多页工作簿并返回包含dataToFind字符串的所有结果。目前,我正在努力使用find和findNext函数。。。下面的内容似乎按照我的要求浏览了所有页面,但它只返回一个结果,一遍又一遍 下面是我的代码 Function searchGrids(contract As String, pbp As String, county As String) As String() Dim datatoFind As String Dim sheetCount A

我正在尝试编写一个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
谢谢


有人问函数应该返回什么值。目前,这并不重要。我所要做的就是访问电子表格的数据,这样我就可以使用它了。然后,我将返回函数中构建的复杂字符串或字符串数组。任何返回的变量都将从其他工作簿中找到的数据生成。如果有更好的方法(比如,返回一个包含术语的所有行的范围),那么我当然对这个方法持开放态度。

这里有一个你可以适应的sub。潜艇在所有的工作表上寻找“快乐”这个词

对于找到的每个实例,记录工作表名称、地址和找到的行的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()方法。

函数应该返回什么值??请参见上面的编辑。