• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Making a couple of changes in search macro code

pemartins

New Member
Hi,

I need help making a couple of changes in a code for a search button in vba.

These are the basic features in this search function:
- there are two buttons, a search button and a clear button to remove the highlight from the highlighted cells found in the previous search;
- the text to search is typed in cell B2;
- it only searches column D;
- after the text to search is typed, it only works by pressing the find button;
- it tells the number of matches found in cell C2.

This is the actual code I have:
Code:
Sub tester()

Dim c1 As Range        'start cell...
Dim r1 As Long          'row found...
Dim r_old As Long      'prior row found...
Dim i As Integer        'for loop...
Dim count As Integer    'number of occurences...
Dim str As String      'string for message box...

Set c1 = Range("D1")    'Start search at this cell...
r1 = 1
r_old = 0
counter = 0

Columns("D:D").Interior.Pattern = xlNone    'Clear all YELLOW cells..

If Not ActiveCell.Column = 4 Then c1.Activate  'If not in Column D... then start from top

'###### Loop Column D for term...
For i = 1 To 5
    On Error GoTo NoneFound 'If none found... go to sub procedure
    r1 = Columns(4).Find(What:=Cells(2, 2).Value, After:=c1, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Row
    On Error GoTo 0    'Default error handling...
   
    Set c1 = Cells(r1, 4)  'Change start cell for Find function...
   
    If r1 > r_old Then
        counter = counter + 1  'Number of occurences...
        str = str & vbCrLf & "Row " & r1

        Cells(r1, 4).Interior.Color = 65535
       
    Else
        Exit For
    End If
   
    r_old = r1
Next i

Cells(2, 3).Value = counter
'MsgBox counter & " occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found in:" & vbCrLf & str

Call Sub1
Exit Sub


'##### If none found... then this Sub procedures is run...
NoneFound:
    Cells(2, 3).Value = 0
    MsgBox "No occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found"
   
End Sub

'###### Activates next found cell...
Sub Sub1()
    Columns(4).Find(What:=Cells(2, 2).Value, After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Activate
End Sub




'###### Clears all YELLOW cells...
Sub Clear()

Columns("D:D").Interior.Pattern = xlNone
End Sub

It works perfectly. Two buttons, one for searching and another to clear. But I wan't to make a couple of changes in it, which are:

1- When there are no searching matches, no window pops-up like it does currently, it just makes a sound (or even nothing) and puts a zero (0) in C2 like it is currently doing (for faster user interface since there will be a lot of consecutive searching using the worksheet);

2- I need the Clear button to work like a reset search button also. I need that when this clear button is clicked, the screen goes back to the beginning of my worksheet, in my case to cell A4, and if possible it also deletes the text typed in B2 and resets the count in C2 to zero (0).

Maybe small changes but I don't have the knowledge or skills to be able to do it. The worksheet is attached to this post.
So can someone help me with it? Thank you very much in advance!
 

Attachments

  • Search Function.xlsm
    23.8 KB · Views: 2
Hi, pemartins!

Considering the code you posted and your advice, I'll try to interfere as little as possible.

For 1) add this line after the label "NoneFound:":
Code:
Exit Sub

For 2) add these lines at the end of procedure "Clear":
Code:
[C2].Value = 0
[A4].Select

Just advise if any issue.

Regards!
 
Thank you very much! Just what I needed!

I added a couple of things more which are also very useful:
- the mentioned sound to play if no matches are found (just added a line with "Beep" before the "Exit Sub" you told me);
- also if no matches are found, the cursor was going to D1 so I added:
Code:
    [A4].Select
    [B2].Select
needed both because the worksheet has the top 3 lines frozen;
- did the same to Clear sub and also added a line to clear the content in cell B2 ([B2].ClearContents).

For a minute I almost felt like a coder, being able to add this small lines on my own! :D

So this is the final code:
Code:
Sub tester()

Dim c1 As Range        'start cell...
Dim r1 As Long          'row found...
Dim r_old As Long      'prior row found...
Dim i As Integer        'for loop...
Dim count As Integer    'number of occurences...
Dim str As String      'string for message box...

Set c1 = Range("D1")    'Start search at this cell...
r1 = 1
r_old = 0
counter = 0

Columns("D:D").Interior.Pattern = xlNone    'Clear all YELLOW cells..

If Not ActiveCell.Column = 4 Then c1.Activate  'If not in Column D... then start from top

'###### Loop Column D for term...
For i = 1 To 5
    On Error GoTo NoneFound 'If none found... go to sub procedure
    r1 = Columns(4).Find(What:=Cells(2, 2).Value, After:=c1, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Row
    On Error GoTo 0    'Default error handling...
  
    Set c1 = Cells(r1, 4)  'Change start cell for Find function...
  
    If r1 > r_old Then
        counter = counter + 1  'Number of occurences...
        str = str & vbCrLf & "Row " & r1

        Cells(r1, 4).Interior.Color = 65535
      
    Else
        Exit For
    End If
  
    r_old = r1
Next i

Cells(2, 3).Value = counter
'MsgBox counter & " occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found in:" & vbCrLf & str

Call Sub1
Exit Sub


'##### If none found... then this Sub procedures is run...
NoneFound:
    Cells(2, 3).Value = 0
    Beep
    [A4].Select
    [B2].Select
    Exit Sub
    'MsgBox "No occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found"
  
End Sub

'###### Activates next found cell...
Sub Sub1()
    Columns(4).Find(What:=Cells(2, 2).Value, After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Activate
End Sub




'###### Clears all YELLOW cells...
Sub Clear()

Columns("D:D").Interior.Pattern = xlNone
[C2].Value = 0
[B2].ClearContents
[A4].Select
[B2].Select
End Sub

But I still have a small issue I had previously, which is that when I put this code into my worksheet (one of some this search function will be used in) everything works but no results are found! I just cannot figure out what should I change to get it to work, probably has something to do with the worksheet name...

Can you check out what's wrong? My worksheet is attached to this post and this code is in module 2. The Search button in the worksheet is before cell B2 and the Reset Search button is before that one and has the Clear sub.

Thank you for everything!
 

Attachments

  • Karaoke - Portugal.xls
    353 KB · Views: 1
Yes that's just it, it's working now! Thank you very much!


I noticed now that the search results don't come out correctly if there are more than 5 matches. And it also highlights only 5 cells tops. Here's a printscreen:
JhKTgIY.jpg


As you can see, the searched word "infantil" has way more matches than the five highlighted and the 5 mentioned in cell C2. But if I keep on clicking the search button it keeps on going to all the matches, not only the mentioned 5.

Can you check out what can be limiting the results to 5?

Thank you all for everything!
 
Hi, pemartins!
Glad you solved it. Thanks for your feedback and for your kind words too. And welcome back whenever needed or wanted. And keep on coding ;)
Regards!
 
Hi ,

The number of results returned is limited because your code has a loop which is :

For i = 1 To 5
.
.
.
Next

If you change your code to :

1. Get the number of results in a variable

2. Use this variable instead of 5 in the above For ... Next loop

then all the returned results will be highlighted.

Narayan
 
Perfect! Working like a charm! :)

Thank you very much once again! This worksheet really became an amazing tool without a doubt!

The only thing I'll add to it now is a button with a pop up "how to use tutorial" window so my 'Djs' (family and friends) can use in case of doubt, so I don't have to be DJing all the time. But I'll create another thread for that since I've been having trouble doing that. Tried to make it using MsgBox lines but I got the error "Too many lines continuations" and was told that I should do something using userform.

Here is the final code so it can be useful for someone else:
Code:
Sub tester()

Dim c1 As Range         'start cell...
Dim r1 As Long          'row found...
Dim r_old As Long       'prior row found...
Dim i As Integer        'for loop...
Dim count As Integer    'number of occurences...
Dim str As String       'string for message box...

Set c1 = Range("D4")    'Start search at this cell...
r1 = 1
r_old = 0
counter = 0

Columns("D:D").Interior.Pattern = xlNone    'Clear all YELLOW cells..

If Not ActiveCell.Column = 4 Then c1.Activate   'If not in Column D... then start from top

'###### Loop Column D for term...
For i = 1 To 5
    On Error GoTo NoneFound 'If none found... go to sub procedure
    r1 = Columns(4).Find(What:=Cells(2, 2).Value, After:=c1, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Row
    On Error GoTo 0     'Default error handling...
   
    Set c1 = Cells(r1, 4)   'Change start cell for Find function...
   
    If r1 > r_old Then
        counter = counter + 1   'Number of occurences...
        str = str & vbCrLf & "Row " & r1

        Cells(r1, 4).Interior.Color = 65535
       
    Else
        Exit For
    End If
   
    r_old = r1
Next i

Cells(2, 3).Value = counter
'MsgBox counter & " occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found in:" & vbCrLf & str

Call Sub1
Exit Sub


'##### If none found... then this Sub procedures is run...
NoneFound:
    Cells(2, 3).Value = 0
    Beep
    [A4].Select
    [B2].Select
    Exit Sub
    'MsgBox "No occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found"
   
End Sub

'###### Activates next found cell...
Sub Sub1()
    Columns(4).Find(What:=Cells(2, 2).Value, After:=ActiveCell, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Activate
End Sub




'###### Clears all YELLOW cells...
Sub Clear()

Columns("D:D").Interior.Pattern = xlNone
[C2].Value = 0
[B2].ClearContents
[A4].Select
[B2].Select
End Sub

Thank you all very much once again!
 
Last edited:
Hi,

I found two issues with the code:

1- Is it possible to add something to the code so that if the "Search" button is clicked with nothing typed in B2 then no search is made and it makes a beep (similar to what happens when no results are found)? Without that if finds and highlights a lot of cells after the music list.

2- If I search something like this "kkkkkkkkkkkkkkkk" I get this error: "Run-time error '91': Object variable or With block variable not set". After pressing debug it highlights "'###### Activates next found cell..." sub in the code.
Do you have any idea why this is happening?

The updated file is attached to this post.

Thank you for the help!
 

Attachments

  • Karaoke - Portugal.xls
    389.5 KB · Views: 2
Thank you so much Narayan!

I just changed the pop-up message to this:
Code:
  [A4].Select
  [B2].Select
  Beep
so it makes an easier and faster user interface.

Also added:
Code:
  [B2].Select
and removed:
Code:
[B2].ClearContents
in the "NoneFound:" sub so that the cell selection goes back to B2 (it was before going to A4 only) and doesn't clear the content in B2. It's best if the search cell is only cleared if the "Reset Search" button is clicked on.

All set! :)

So this is the code (the final one I really hope!):
Code:
Sub tester()

Dim searchcell As Range
Dim c1 As Range        'start cell...
Dim r1 As Long          'row found...
Dim r_old As Long      'prior row found...
Dim i As Integer        'for loop...
Dim count As Integer    'number of occurences...
Dim str As String      'string for message box...

Set searchcell = Cells(2, 2)
If searchcell.Value <> vbNullString Then
  Set c1 = Range("D4")    'Start search at this cell...
  r1 = 1
  r_old = 0
  counter = 0

  Columns("D:D").Interior.Pattern = xlNone    'Clear all YELLOW cells..

  If Not ActiveCell.Column = 4 Then c1.Activate  'If not in Column D... then start from top

  Number_of_results = Application.WorksheetFunction.CountIf(Columns("D:D"), "*" & Cells(2, 2).Value & "*")
  If Number_of_results > 0 Then
'    ###### Loop Column D for term...
      For i = 1 To Number_of_results
          On Error GoTo NoneFound 'If none found... go to sub procedure
     
          r1 = Columns(4).Find(What:=Cells(2, 2).Value, After:=c1, LookIn:=xlValues, _
                              LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                              MatchCase:=False).Row
          On Error GoTo 0    'Default error handling...

          Set c1 = Cells(r1, 4)  'Change start cell for Find function...

          If r1 > r_old Then
            counter = counter + 1  'Number of occurences...
            str = str & vbCrLf & "Row " & r1

            Cells(r1, 4).Interior.Color = 65535
     
          Else
            Exit For
          End If

          r_old = r1
      Next i

      Cells(2, 3).Value = counter
'    MsgBox counter & " occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found in:" & vbCrLf & str

      Call Sub1
      Exit Sub
  End If

'  ##### If none found... then this Sub procedures is run...
NoneFound:
  Cells(2, 3).Value = 0
  Beep
  [A4].Select
  [B2].Select
  Exit Sub
'  MsgBox "No occurences of " & Chr(34) & Cells(2, 2).Value & Chr(34) & " found"
Else
  'MsgBox "No valid search text entered , exiting...", vbExclamation
  [A4].Select
  [B2].Select
  Beep
End If
End Sub

'###### Activates next found cell...
Sub Sub1()
    Columns(4).Find(What:=Cells(2, 2).Value, After:=ActiveCell, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False).Activate
End Sub




'###### Clears all YELLOW cells...
Sub Clear()

Columns("D:D").Interior.Pattern = xlNone
[C2].Value = 0
[B2].ClearContents
[A4].Select
[B2].Select
End Sub

And attached to this post is the very last version of the file.

Also posted here a clean version of the file, without my song list.

Once again thank you all for everything!
 

Attachments

  • Karaoke - Portugal.xls
    388 KB · Views: 5
Last edited:
Back
Top