I wrote a macro that will search for a string in all sheets of the excel file. This macro activates the first sheet, as well as the cell on the sheet that contains the search string. If it is not found, it will display a message. This macro is working fine. I wanted to extend this functionality to cover all sheets containing this line, not the first. So I changed the macro, but it does not work as expected. I gave the code below and also commented in the place where it shows the error.
Dim sheetCount As Integer
Dim datatoind
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 ie following code is not executed
If InStr (1, str, datatoFind) Then
HasMoreValues = True
Exit for
End if
Next counter
End function
samar source
share