Как искать строку во всех листах книги Excel? - PullRequest
7 голосов
/ 19 января 2011

Я написал макрос, который будет искать строку во всех листах книги Excel.Этот макрос активирует первый лист, а также ячейку на листе, которая содержит строку поиска.Если не найден, он покажет сообщение.

Я хочу расширить эту функциональность, чтобы охватить все листы, содержащие эту строку, а не только первый.Поэтому я изменил макрос, но он не работает, как ожидалось.Я дал приведенный ниже код, а также прокомментировал место, где он показывает ошибку.

Dim sheetCount As Integer
Dim datatoFind

Sub Button1_Click()

Find_Data

End Sub

Private Sub Find_Data()
    Dim counter As Integer
    Dim currentSheet As Integer
    Dim notFound As Boolean
    Dim yesNo As String

    notFound = True

    On Error Resume Next
    currentSheet = ActiveSheet.Index
    datatoFind = InputBox("Please enter the value to search for")
    If datatoFind = "" Then Exit Sub
    sheetCount = ActiveWorkbook.Sheets.Count
    If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind)
    For counter = 1 To sheetCount
        Sheets(counter).Activate

        Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

        If InStr(1, ActiveCell.Value, datatoFind) Then
            If HasMoreValues(counter + 1) Then 'Not completing the method and directly entering
                yesNo = MsgBox("Do you want to continue search?", vbYesNo)
                If yesNo = vbNo Then
                    notFound = False
                    Exit For
                End If
            End If
            Sheets(counter).Activate
        End If
    Next counter
    If notFound Then
        MsgBox ("Value not found")
        Sheets(currentSheet).Activate
    End If
End Sub

Private Function HasMoreValues(ByVal sheetCounter As Integer) As Boolean
    HasMoreValues = False
    Dim str As String

    For counter = sheetCounter To sheetCount
        Sheets(counter).Activate

        str = Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Value 'Not going further than this i.e. following code is not executed

        If InStr(1, str, datatoFind) Then
            HasMoreValues = True
            Exit For
        End If
    Next counter
End Function

Ответы [ 2 ]

6 голосов
/ 26 января 2011

Я смог решить свою проблему и выложил код для тех, кому это может понадобиться

Dim sheetCount As Integer
Dim datatoFind

Sub Button1_Click()

    Find_Data

End Sub

Private Sub Find_Data()
    Dim counter As Integer
    Dim currentSheet As Integer
    Dim notFound As Boolean
    Dim yesNo As String

    notFound = True

    On Error Resume Next
    currentSheet = ActiveSheet.Index
    datatoFind = StrConv(InputBox("Please enter the value to search for"), vbLowerCase)
    If datatoFind = "" Then Exit Sub
    sheetCount = ActiveWorkbook.Sheets.Count
    If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind)
    For counter = 1 To sheetCount
        Sheets(counter).Activate

        Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

        If InStr(1, StrConv(ActiveCell.Value, vbLowerCase), datatoFind) Then
            notFound = False
            If HasMoreValues(counter) Then
                yesNo = MsgBox("Do you want to continue search?", vbYesNo)
                If yesNo = vbNo Then
                    Sheets(counter).Activate
                    Exit For
                End If
            Else
                Sheets(counter).Activate
                Exit For
            End If
            Sheets(counter).Activate
        End If
    Next counter
    If notFound Then
        MsgBox ("Value not found")
        Sheets(currentSheet).Activate
    End If
End Sub

Private Function HasMoreValues(ByVal sheetCounter As Integer) As Boolean
    HasMoreValues = False
    Dim str As String
    Dim lastRow As Long
    Dim lastCol As Long
    Dim rRng  As Excel.Range

    For counter = sheetCounter + 1 To sheetCount
        Sheets(counter).Activate

        lastRow = ActiveCell.SpecialCells(xlLastCell).Row
        lastCol = ActiveCell.SpecialCells(xlLastCell).Column

        For vRow = 1 To lastRow
            For vCol = 1 To lastCol
                str = Sheets(counter).Cells(vRow, vCol).Text
                If InStr(1, StrConv(str, vbLowerCase), datatoFind) Then
                    HasMoreValues = True
                    Exit For
                End If
            Next vCol

            If HasMoreValues Then
                Exit For
            End If
        Next vRow

        If HasMoreValues Then
            Sheets(sheetCounter).Activate
            Exit For
        End If
    Next counter
End Function
0 голосов
/ 24 января 2011

Проблема в том, что Cells.Find возвращает диапазон. Когда вы используете его в своей функции HasMoreValues, вы используете это так:

Cells.Find(...).Value

Но возвращенный диапазон не преобразуется в .value правильно. Вы можете исправить это, используя .text вместо .value, например:

Cells.Find(...).text

Или полностью:

str = Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
  :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
  False, SearchFormat:=False).text

Чтобы быть полностью правильным, вам, вероятно, следует set результат поиска в переменной Range, а затем обращаться к нему через него, если поиск Find ничего не даст. Однако согласно документации Cells.Find всегда возвращает диапазон из одной ячейки, так что с вами может быть все в порядке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...