Here's the relevant parts of my code I'm having trouble with.
Sub Find_Target()
Dim DayNum As Long
Dim TargetName As String
Dim TargetDay As Range
Dim found As Variant
DayNum = Cells(1, 9)
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
TargetDay.Activate
Set found = TargetDay.Find(DayNum, LookIn:=xlValues)
If found Is Nothing Then
MsgBox "Nothing found!"
Else
TargetDay.Select
End If
End Sub
Column A contains a mix of merged and unmerged cells. Cells(1, 9) contains a date in general format. Periodically in column A/B will be a merged cell containing that same number, but in custom number format "dddd". The find command works if I change the number format to general, but otherwise found is Nothing.
I've tried playing with the FindFormat option, but didn't have any luck there.
A bit unclear from the question, so I'm assuming that you have a number in cell I1 and you want to find the first cell with on the same day of the month. Assuming that's the case, you can just loop through the range and compare against the day directly:
Sub Find_Target()
Dim DayNum As Long
Dim TargetDay As Range
Dim found As Range
DayNum = Cells(1, 9)
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
Dim row As Long, col As Long
For row = 1 To TargetDay.Rows.Count
For col = 1 To TargetDay.Columns.Count
If IsDate(TargetDay.Cells(row, col).Value) Then
If Day(CDate(TargetDay.Cells(row, col).Value)) = DayNum Then
Set found = TargetDay.Cells(row, col)
Exit For
End If
End If
Next col
If Not found Is Nothing Then Exit For
Next row
If found Is Nothing Then
MsgBox "Nothing found!"
Else
found.Select
End If
End Sub
If I1 is something else, it should be trivial to modify - the key is explicitly treating the cell values as dates in VBA.
You need to .Find for LookAt:=xlFormulas and look for a Date type var, not a Long. Throw the following at your data.
Sub Find_Target()
Dim iDayNum As Long, sDayNum As String, dDayNum As Date
Dim foundI As Variant, foundS As Variant, foundD As Variant
Dim TargetDay As Range
iDayNum = Cells(1, 9)
sDayNum = Format(Cells(1, 9), "mm/dd/yyyy")
dDayNum = Cells(1, 9) 'I might even use CDate(Cells(1, 9).Value) as a reminder
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
Set foundI = TargetDay.Find(iDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
Set foundS = TargetDay.Find(sDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
Set foundD = TargetDay.Find(dDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
If foundI Is Nothing Then
MsgBox "As a Long - Nothing found!"
Else
MsgBox "As a Long - Found!"
End If
If foundS Is Nothing Then
MsgBox "As a String - Nothing found!"
Else
MsgBox "As a String - Found!"
End If
If foundD Is Nothing Then
MsgBox "As a Date - Nothing found!"
Else
MsgBox "As a Date - Found!"
End If
End Sub
You should have no problem finding the matching date var no matter whether it is formatted as dddd or anything else.
Related
Sub FindValue()
Dim firstAddress As String
Dim Expense As String
Dim rRange As Range
Dim FirstrngFnd As Range
Dim x As Integer
Dim y As Integer
Dim z As Integer
Workbooks.Open FileName:= _
"D:\My Documents\Excel Files\AA Credit Card\1008.xlsx" 'A worksheet with several columns - Column G (Column 7) is a list of "expenses".
Workbooks.Open FileName:= _
"D:\My Documents\Excel Files\Credit Card Analysis.xlsx" 'A worksheet with "expenses" listed in random order in Column A (Column1)
Windows("Credit Card Analysis.xlsx").Activate
ActiveWindow.Panes(1).Activate
Expense = Application.InputBox("Select the required expense from Column A") 'Pick an "expense" from a list in Column A
'Open the first file in the first folder
Windows("1008.xlsx").Activate
ActiveWindow.Panes(1).Activate
'Establish the first and last rows in Column A (which contain a list of dates by increasing date): required to establish the search range
Set rRange = Range("A1", Cells(Rows.Count, 1).End(xlUp))
For Each rCell In rRange
If IsDate(rCell) Then
rCell(2, 1).Select
Exit For
End If
Next rCell
x = (ActiveCell.Row - 1) 'This finds the FIRST row in the file with a date in it
y = Cells(Rows.Count, 1).End(xlUp).Row 'This finds the LAST row in the file with a date in it
My_Workbook = ActiveWorkbook.Name 'Holds the current Workbook name
'Move over to the "analysis" column (G) (Column 7)
With Worksheets(1).Range(Cells(x, 7), Cells(y, 7))
Set FirstrngFnd = .Find(Expense, LookIn:=xlValues, LookAt:=xlPart) 'Finds the first occurrence of "expense"
If Not FirstrngFnd Is Nothing Then 'if the "expense" isn't listed then goto Line400
firstAddress = FirstrngFnd.Address
Do 'DO WHATEVER IS REQUIRED IN THIS SECTION: FROM "DO" TO "Set FirstrngFnd = .FindNext(FirstrngFnd)"
z = FirstrngFnd.Row
FirstrngFnd.Value = "Mike" 'IF YOU OMIT THIS LINE THEN ALL THE VALUES REMAIN AT "expense", SO THE PROGRAM JUST GOES ROUND (AND ROUND) AGAIN.
Set FirstrngFnd = .FindNext(FirstrngFnd)
Loop While Not FirstrngFnd Is Nothing
End If
End With
End Sub
If I remove the line "FirstrngFnd.Value = "Mike" then the values in Golumn G never change so when the program gets to the end of the file, it just goes round again.
How can I get it to recognise it's been through the file once, and to move on?
Please, modify:
Loop While Not FirstrngFnd Is Nothing
in this way:
Loop While Not FirstrngFnd Is Nothing And FirstrngFnd.Address <> firstAddress
Find in an Endless Loop
This covers the case when you are using the Find method (incl. FIndNext) to find all occurrences of a value in a range, but you don't want to change them and you also don't want to end up in an endless loop.
To simplify, the procedures use Sheet1 (CodeName) and the range "A1:A3" and "Yes" as the criteria.
Copy them into a new workbook.
Test first both procedures without values, then put in some "Yes" values (without the double quotes) in the cells. You can also change the range to e.g. A1:A10, to better understand.
The Code
Option Explicit
' To exit the endless loop, press and hold down the ESC key.
Sub testEndlessLoop()
Dim rng As Range
Dim cel As Range
Set rng = Sheet1.Range("A1:A3")
Set cel = rng.Find( _
What:="Yes", _
After:=rng(rng.Cells.Count), _
LookIn:=xlFormulas)
' Assuring that a cel containing "Yes" has been found. Once it has
' been found, find will always find an occurrence of "Yes" whether
' there is one, two or three occurrences in the range,
' which will result in an endless loop (Do Loop).
If Not cel Is Nothing Then
' A cell containing "Yes" has been found.
Do
MsgBox "Found ""Yes"" in cell '" & cel.Address & "'."
' Find the next occurrence of "Yes"
Set cel = rng.FindNext(cel)
' 'While Not cel Is Nothing' is redundant because 'cel' will
' never be 'Nothing' anyway, which is ensured previously with
' 'If Not cel Is Nothing Then'.
Loop While Not cel Is Nothing
Else
' A cell containing "Yes" has not been found.
MsgBox "No occurrences found."
End If
End Sub
Sub testWorkingLoop()
Dim rng As Range
Dim cel As Range
Dim FirstAddress As String
Set rng = Sheet1.Range("A1:A3")
Set cel = rng.Find( _
What:="Yes", _
After:=rng(rng.Cells.Count), _
LookIn:=xlFormulas)
If Not cel Is Nothing Then
' A cell containing "Yes" has been found.
' Write the range address of the first found occurrence to a variable.
FirstAddress = cel.Address
Do
' This is where you do stuff when "Yes" is found.
MsgBox "Found ""Yes"" in cell '" & cel.Address & "'."
' Most often you don't want to change the found cell,
' but you want to change another cell in the same row,
' e.g. write to the cell in column 'B'.
cel.Offset(0, 1).Value = "Found a ""Yes""."
' This is where you do stuff when "Yes" is found.
' Find the next occurrence of "Yes"
Set cel = rng.FindNext(cel)
' Again, 'cel' will never be 'Nothing'.
Loop While cel.Address <> FirstAddress
Else
' A cell containing "Yes" has not been found.
MsgBox "No occurrences found."
End If
End Sub
I have a VBA Module that is trying to get all occurrences of a date in column G in one sheet. After finding the row of the occurrence, I'm saving other values from the sheet on the same row from different columns, i.e. bldg, and room, and numPerson.
What I'm trying to do after that is to get the call a function with the date, numPerson, bldg and room as arguments. The function FillDateCapacitiesInOccupancySheet should go to a different sheet and search column B for the bldg, get that row, then look for the room on the same row and place the numPpl on the row under the correct column for the date that was given. In the following code I get an Error 91 on the Loop While statement if I remove
If FoundCell Is Nothing Then
MsgBox "No Found Cell Address", vbInformation
Exit Sub
End If
The click function works fine if I remove the call to the function FillDateCapacitiesInOccupancySheet, but otherwise I get an error. Either the FoundCell or myRange is empty but I'm not sure why or how to fix it.
Sub ConflictButton_Click()
Dim sourceColumn As Range
Dim targetColumn As Range
Dim beginningDate As String, stringDate As String, month As String, day As String, year As String
Dim dates As Date
Dim occWS As Worksheet, excepWS As Worksheet
Dim beginningDateCell As Range, addDatesCells As Range, FindDateRow As Range
Dim datesArray(1 To 7) As Date, stringDatesArray(1 To 7) As String
Dim lLoop As Long, findRowNumber As Long
Dim tempMonth As String, tempDay As String
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'Copy Building, Room, and Max Capacity Columns from sheet Table to sheet OccupancyByDate
Set sourceColumn = ThisWorkbook.Worksheets("Table").Columns("B:D").Rows("3:500")
Set targetColumn = ThisWorkbook.Worksheets("OccupancyByDate").Columns("B:D").Rows("3:500")
sourceColumn.Copy Destination:=targetColumn
'open FindConflictDates Form
FindConflictDatesForm.Show
'Set OccupancyByDate sheet Column E Row 2 (Column Header) to the Week Starting Date,
'get the week beginning string from what was saved from the FindConflictDatesForm
If WeekBeginningString <> "" Then
beginningDate = WeekBeginningString
WeekBeginningDate = CDate(beginningDate) ' convert String to Date
Set occWS = ThisWorkbook.Sheets("OccupancyByDate")
Set excepWS = ThisWorkbook.Sheets("Telework Exceptions")
' Fill the 7 dates into header in OccupanyByDate sheet Columns E - K row 2
Dim i As Integer
i = 1
For j = 5 To 11 ' From column E(5) to K (11)
dates = WeekBeginningDate - Weekday(WeekBeginningDate, vbUseSystemDayOfWeek) + i
occWS.Cells(2, j).Value = Format(dates, "dd-mmm-yyyy") ' write dates to OccByDate sheet
'Save dates to datesArray
datesArray(i) = dates
stringDate = CStr(dates) ' convert date to string
If Mid(stringDate, 2, 1) <> "/" Then ' 2 digit month
tempMonth = Left(stringDate, 2)
Else
tempMonth = Left(stringDate, 1) ' 1 digit month
month = GetMonthAbbreviation(tempMonth)
End If
If Left(Right(stringDate, 7), 1) <> "/" Then '2 digit day
day = Left(Right(stringDate, 7), 2)
Else
day = Left(Right(stringDate, 6), 1) ' 1 digit day
' day = Mid(stringDate, 4, 2)
End If
year = Right(stringDate, 4)
stringDatesArray(i) = day & "-" & month & "-" & year
i = i + 1 ' Add 1 to increment date of week
Next j
''''''''''''''''''''''''
' Search for dates on the TW Exception Sheet
Dim numPerson As Long, Bldg As String, Room As String, foundDate As String
numPerson = 0
For i = LBound(datesArray) To UBound(datesArray)
'Search for datesArray(i) on TW Exceptions sheet
Set myRange = excepWS.Range("G:G")
Set LastCell = myRange.Cells(myRange.Cells.count)
Set FoundCell = myRange.Find(what:=stringDatesArray(i), after:=LastCell, LookIn:=xlValues)
If Not FoundCell Is Nothing Then ' if value found in column
FirstFound = FoundCell.Address
findRowNumber = FoundCell.Row 'get row number of the found date in the column on TW Excep sheet
foundDate = FoundCell.Text 'get text value of first occurence of new date found in column
Do ' Find additional occurences of date in the sheet column
findRowNumber = FoundCell.Row
If FoundCell.Offset(0, -3).Value = 1 Then
numPerson = 1
End If
If FoundCell.Offset(0, -2).Value = 1 Then
numPerson = 1
End If
Bldg = FoundCell.Offset(0, 3).Text
Room = FoundCell.Offset(0, 4).Text
FillDateCapacitiesInOccupancySheet foundDate, numPerson, Bldg, Room 'if i remove this line I don't get an error
Set FoundCell = myRange.FindNext(FoundCell)
If FoundCell Is Nothing Then
MsgBox "No Found Cell Address", vbInformation
Exit Sub
End If
Loop While (FoundCell.Address <> FirstFound)
End If
Next i 'Get next dateArray value
End If 'End if WeekBeginningString <> ""
End Sub
Sub FillDateCapacitiesInOccupancySheet(fndDate As String, numPpl As Long, Buildg As String, Rm As String)
Dim occWS As Worksheet
Dim FndCell As Range, rng As Range
Dim myNewRange As Range, LastCell As Range
Dim foundBldg As String
Dim findRowNumber As Long, count As Long
Dim dateOffset As Integer
Dim FirstFound As String
count = 0
Set occWS = ThisWorkbook.Sheets("OccupancyByDate")
Set myNewRange = occWS.Range("B:B") ' search in building column
Set LastCell = myNewRange.Cells(myNewRange.Cells.count)
Set FndCell = myNewRange.Find(what:=Buildg, after:=LastCell, LookIn:=xlValues)
If Not FndCell Is Nothing Then ' if value found in column
FirstFound = FndCell.Address
findRowNumber = FndCell.Row 'get row number of the found building in the column on OccByDate sheet
foundBldg = FndCell.Text 'get text value of first occurence of new building found in column
Do ' Find additional occurences of date in the sheet column
findRowNumber = FndCell.Row
If FndCell.Offset(0, 1).Text = Rm Then ' if room passed into function equals room for the building
'Find the date column for the date passed into function
For j = 5 To 11 ' From column E(5) to K (11)
If occWS.Cells(2, j).Text = fndDate Then
dateOffset = j - 2
count = FndCell.Offset(0, dateOffset).Value + numPpl
' write count to cell
FndCell.Offset(0, dateOffset).Value = count
End If
Next j
End If
Set FndCell = myNewRange.FindNext(FndCell)
Loop While (FndCell.Address <> FirstFound)
End If
End Sub
Any help would be greatly appreciated.
I get an Error 91 on the Loop While statement
Here:
Set FndCell = myNewRange.FindNext(FndCell)
Loop While (FndCell.Address <> FirstFound)
If that Range.FindNext call doesn't find anything, FndCell is Nothing when the While condition gets evaluated, and that would be where error 91 is being raised; the If Not FndCell Is Nothing Then parent block means nothing as soon as FndCell is re-assigned.
You need to bail out when FndCell is Nothing. Consider using Exit Do for this:
If FndCell Is Nothing Then Exit Do
Loop While FndCell.Address <> FirstFound
Only exiting the smaller scope conveys intent better than exiting the entire procedure scope here, I find - even if all that's left to execute [for now] is an End Sub statement.
Consider declaring j and having Option Explicit at the top of the module, too!
I think I've tried literally everything including converting the Timestamp back into date using CDate
The code is a test I'm running to get the Range.Find to work in the first place. The file in which i look up the time stamp is formatted as special dd.mm.yyyy hh:mm for example 01.01.2019 00:00 whereas in the formula bar it is 01.01.2019 00:00:00
EDIT : Removed the quotes around sDate, a copy and paste mistake
Sub trial()
Dim r As Range
Dim sDate As String
Dim find As Range
Dim col As Long
Set r = ThisWorkbook.Worksheets("INPUT_WIND").Range("d11")
col = ThisWorkbook.Worksheets("INPUT_WIND").Range("d11").Column
sDate = Format(r.Offset(, -col + 2), "dd.mm.yyyy hh:mm")
Debug.Print sDate
Set find = Workbooks("FINO raw-010119-310819").Worksheets(1).Range("A:A").find(sDate, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=True)
If Not find Is Nothing Then
Debug.Print find.Offset(, 1)
Else
MsgBox "nicht gefunden"
End If
End Sub
Try this fix
Sub trial()
Dim r As Range
Dim sDate As String
Dim find As Range
Dim col As Long
Set r = Range("d11")
col = Range("d11").Column
sDate = r.Offset(, -col + 2)
Debug.Print sDate
Set find = Worksheets(1).Range("A:A").find(CDate(sDate), LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=True)
If Not find Is Nothing Then
Debug.Print find.Offset(, 1)
Else
MsgBox "nicht gefunden"
End If
End Sub
I have a macro that loops through cells of one sheet, looks for that value in another sheet, and then highlights the row if they match. I'd like to add a message box that would pop up if a matching value is not found. I know this is a simple problem, but I'm having trouble figuring out in which loop to put my booleans.
Sub MarkXfer_noX()
Dim rng As Range
Dim rng2 As Range
Set rng = Worksheets("Transferred Routings").UsedRange
Dim i As Integer
Dim j As Integer
Dim ProdCI As String
Dim found As Boolean
Dim intRowCount As Integer
intRowCount = Sheets("Transferred Routings").UsedRange.Rows.count
For i = 2 To intRowCount
If rng.Cells(i, 1) <> "" Then ProdCI = rng.Cells(i, 1) 'get the ProdCI number from column A if not blank
Worksheets("All_ProCI").Activate 'activate main page
Set rng2 = Worksheets("All_ProCI").UsedRange 'select a range on the main page
For j = 2 To rng2.Rows.count 'from row 2 to the end
If rng2.Cells(j, 2) = ProdCI Then 'if the ProdCI in column B matches the one we picked,
Call FillCell(j) 'call a sub in a different module and give it our current row
found = True
Else
found = False
End If
Next
Next
If found = False Then
MsgBox (ProdCI & " not found") 'Display a message if one of the items wasn't found on the main page. Currently has an error where the last one in the list always pops up.
Else
End If
End Sub
Right now it always shows a msgbox with the last value in the range no matter what.
Thanks all, here is the updated working code using the Find function
Sub MarkXfer_Find()
'Re-tooled to use the .Find function instead of looping through each
Dim rng As Range
Dim rng2 As Range
Set rng = Worksheets("Transferred Routings").UsedRange
Dim i As Integer
Dim ProdCI As String
Dim intRowCount As Integer
Dim intRowCount2 As Integer
Dim aCell As Range
intRowCount = Sheets("Transferred Routings").UsedRange.Rows.count
For i = 2 To intRowCount
If rng.Cells(i, 1) <> "" Then ProdCI = rng.Cells(i, 1) 'get the ProdCI number from column A if not blank
Worksheets("All_ProCI").Activate 'activate main page
Set rng2 = Worksheets("All_ProCI").UsedRange 'select a range on the main page
intRowCount2 = Worksheets("All_ProCI").UsedRange.Rows.count
'use the Find function to put a value in aCell
Set aCell = rng2.Range("B1:B" & intRowCount2).Find(What:=ProdCI, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
'MsgBox ProdCI & " found"
Call FillCell(aCell.row)
Else 'If aCell is blank display msgbox
MsgBox "ProdCI """ & ProdCI & """ not found"
End If
Next
End Sub
I have been driving myself mad with this for a day, searched high and low, and am probably trying to be too cute so am totally stuck.
I am trying to run a simple if then
If a cell contains "%" I'd like it to do one thing, and if not another. For reasons I don't understand I can't get it to work out. I've clearly taken a couple ideas from elsewhere but still can't get it to work.
Complicating factors- I don't want to run this on the whole column, just a table, so it is embedded in a larger sub using lots or relative ActiveCells. I never know where in the A column I am going to run into the "% Change" so the Range always has to be variable. I want VBA/VBE to do something different when it comes upon a cell with the "%" in it. SO
Here is what the raw data looks like
Initial Value (6/30/06)
Value (12/31/06)
Net Additions (9/30/07)
Withdrawal (12/07)
Value (12/31/07)
Withdrawal (2008)
Value (12/31/08)
Addition (8/26/09)
Value (12/31/09)
Value (12/31/10)
Value (12/30/11)
Value (3/31/12)
% Change 1st Quarter
% Change Since Inception
But when I run the following it gets stuck in a bad loop where it should have pulled out into the "If Then" as opposed to the "Else" part of the sub.
Sub IfTest()
'This should split the information in a table up into cells
Dim Splitter() As String
Dim LenValue As Integer 'Gives the number of characters in date string
Dim LeftValue As Integer 'One less than the LenValue to drop the ")"
Dim rng As Range, cell As Range
Set rng = ActiveCell
Do While ActiveCell.Value <> Empty
If InStr(rng, "%") = True Then
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "% Change")
ActiveCell.Offset(0, 10).Select
ActiveCell.Value = Splitter(1)
ActiveCell.Offset(0, -1).Select
ActiveCell.Value = "% Change"
ActiveCell.Offset(1, -9).Select
Else
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "(")
ActiveCell.Offset(0, 9).Select
ActiveCell.Value = Splitter(0)
ActiveCell.Offset(0, 1).Select
LenValue = Len(Splitter(1))
LeftValue = LenValue - 1
ActiveCell.Value = Left(Splitter(1), LeftValue)
ActiveCell.Offset(1, -10).Select
End If
Loop
End Sub
All help is appreciated, thank you!
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.
The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
you never change the value of rng so it always points to the initial cell
copy the Set rng = rng.Offset(1, 0) to a new line before loop
also, your InStr test will always fail
True is -1, but the return from InStr will be greater than 0 when the string is found. change the test to remove = True
new code:
Sub IfTest()
'This should split the information in a table up into cells
Dim Splitter() As String
Dim LenValue As Integer 'Gives the number of characters in date string
Dim LeftValue As Integer 'One less than the LenValue to drop the ")"
Dim rng As Range, cell As Range
Set rng = ActiveCell
Do While ActiveCell.Value <> Empty
If InStr(rng, "%") Then
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "% Change")
ActiveCell.Offset(0, 10).Select
ActiveCell.Value = Splitter(1)
ActiveCell.Offset(0, -1).Select
ActiveCell.Value = "% Change"
ActiveCell.Offset(1, -9).Select
Else
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "(")
ActiveCell.Offset(0, 9).Select
ActiveCell.Value = Splitter(0)
ActiveCell.Offset(0, 1).Select
LenValue = Len(Splitter(1))
LeftValue = LenValue - 1
ActiveCell.Value = Left(Splitter(1), LeftValue)
ActiveCell.Offset(1, -10).Select
End If
Set rng = rng.Offset(1, 0)
Loop
End Sub
For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub