PGSystemTester

VBA Find and Loop Example

Jul 6th, 2017
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sub Find_Example_WithLoop()
  2.     Dim CL As Range, FirstFoundAddress As String
  3.     Dim WS As Worksheet: Set WS = ActiveSheet
  4.  
  5. 'FIND SYNTAX By PGCodeRider
  6.  
  7. 'LOOKIN: xlFormulas , xlValues , or xlNotes
  8. 'LookAT: xlWhole or XlPart
  9. 'SearchOrder: xlByRows or xlByColumns
  10. 'SearchDirection: xlNext or xlPrevious
  11. 'MatchCase: True or False
  12. 'FindNext - Continues a search that was begun with the Find method. Finds the next cell that matches those same conditions.
  13.  
  14.     ' Find first instance on sheet
  15.    Set CL = WS.Cells.Find(What:="BOOOOM", _
  16.         After:=WS.Cells(1, 1), _
  17.         LookIn:=xlFormulas, _
  18.         LookAt:=xlPart, _
  19.         SearchOrder:=xlByRows, _
  20.         SearchDirection:=xlNext, _
  21.         MatchCase:=False, _
  22.         SearchFormat:=False)
  23.     If Not CL Is Nothing Then
  24.         ' if found, remember location, else ends if-statement
  25.        
  26.         FirstFoundAddress = CL.Address
  27.  
  28.         Do
  29.             'DO SOMETHING!!
  30.            
  31.             ' find next instance
  32.            Set CL = WS.Cells.FindNext(After:=CL)
  33.             ' repeat until finds original cell
  34.        Loop Until FirstFoundAddress = CL.Address
  35.        
  36.     End If
  37.     Next
  38. End Sub
Add Comment
Please, Sign In to add comment