Find method raise error 91 in excel Macro - excel

I use a find method in the Excel macro for searching VLOOKUP in a cell, my goal is I need to know which formula that does not contain VLOOKUP, my method was running well, until in a cell there was
no VLOOKUP and macro kept debugging with the Run time error '91'
My question is how should I write the macro correctly so I wont get the debug until the activecell
contains *, below is my macro:
Sub findvlookup()
Do While Not ActiveCell.Value = "*"
If Selection.Find(What:="VLOOKUP", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate Then
ActiveCell.Offset(1, 0).Select
End If
Loop
End Sub
Thanks for the help

You don't need a loop to find the first occurrence of your 'What:=" string
Dim fndVL as Range
fndVL = Selection.Find(What:="VLOOKUP", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not fndVL is Nothing Then
MsgBox "Found it"
Else
NsgBox "Not found"
End If
If you want to find subsequent instances then have a look at FindNext and possibly use this within a loop.

Sub findvlookup()
Dim rngFind As Range
Do While Not ActiveCell.Value = "*"
Set rngFind = Selection.Find(What:="VLOOKUP", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not rngFind Is Nothing Then
ActiveCell.Offset(1, 0).Select
Else
Exit Sub
End If
Loop
End Sub

You are using Find method that technical details are Here.
You can find (in example) that:
Common Err.Numbers (9, 91) : the specified text wasn't in the target workbook.
And if you have a cell with an error value you will have another type of errors: like #Value

Related

VBA Array Formula and Goal Seek in IF Then Statement

This code doesnt run. It first looks into a range, if 0 does not exist then select least negative value, by using array formula. Then goal seek to set selected cell to 0 by changing value of a cell on same row, left 4 columns. If 0 exists do nothing. Any help appreciated
Sub Test()
Dim Cel As Integer
For Each Cel In ThisWorkbook.Sheets("Sheet1").Range("V17:V57")
If Cel.Value <> 0 Then
Cel.Find(Application.WorksheetFunction.FormulaArray(MAX(IF(V17:V57<=0,V17:V57),MIN(V17:V57))))
Cel.Select
Cel.GoalSeek Goal:=0, ChangingCell:=Cel.Offset(0, -4)
End If
Next Cel
End Sub
Looks like the previous comments/responses were deleted. Here's the latest version of the code, modified as per previous responses. Still doesn't run. I removed .Activate at the end of Cel.Find. Now there's a compile Syntax error. Any help apprciated
Sub Test()
Dim Cel As Range
For Each Cel In ThisWorkbook.Sheets("Sheet1").Range("V17:V57").Cells
If Cel.Value <> 0 Then
Cel.Find(What:="MAX(IF(V17:V57<=0,V17:V57),MIN(V17:V57))", After:= _
ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Cel.GoalSeek Goal:=0, ChangingCell:=Cel.Offset(0, -4)
End If
Next Cel
End Sub
Just delete the parentheses in your Find method.
Use:
Cel.Find What:="MAX(IF(V17:V57<=0,V17:V57),MIN(V17:V57))", After:= _
ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False
Instead of:
Cel.Find(What:="MAX(IF(V17:V57<=0,V17:V57),MIN(V17:V57))", After:= _
ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

Ms Excel Replace value with the average of the previous and next values

I'm working with hourly weather data in Excel that has each hour of every day of the year along with the corresponding temperature value that was recorded.
Some of the values weren't recorded, and instead show up as just an "M" on the spreadsheet. For example, A32 = 28, A33 = M, A34 = 30. I want to replace that "M" with a formula to take the average of the previous and next values. I know how to do this manually, but I am having difficulty writing a Macro to find all the M's in the spreadsheet, then auto-replace it as stated above.
My main obstacle is getting excel to use the correct values when replacing the "M".
Here is my code
Sub MReplace()
'
' MReplace Macro
'
'
ActiveCell.Select
Cells.Find(What:="M", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.Offset(-8, 1).Range("A1").Select
Cells.Find(What:="M", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True _
, SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.Replace What:="M", Replacement:="[****This is what I am having difficulty with****]", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Find(What:="M", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True _
, SearchFormat:=False).Activate
End Sub
I have heard of something that you can put in to the code that can address the selected cell. I think it's cell() but I am not sure. Maybe that is a way to get it to work better?
Try this code:
Sub MReplace()
Dim ws As Worksheet
Dim cel As Range
Dim firstAddress As String
Set ws = ActiveSheet
Set cel = ws.Range("A:A").Find("M")
If Not cel Is Nothing Then
firstAddress = cel.Address
Do
cel.Value = (cel.Offset(1) + cel.Offset( -1)) / 2
Set cel = ws.Range("A:A").FindNext(cel)
hr = False
If Not cel Is Nothing Then
If cel.Address <> firstAddress Then
hr = True
End If
End If
Loop While hr
End If
End Sub
It loops through all the cells containing "M" and replaces it with the average of the one on the right and the one on the left. It will error on any that are in the first column as there is no column to the left.

Loop finishing with error

I need to look for each row that has the phrase " Total" in it, insert rows above and below it, format other cells in and around that same row, remove the phrase " Total" from the cell, and repeat the process for all other rows in the report.
The macro I've developed, once it's found and replaced all of the instances of " Total", I get the Run-time error '91': Object variable or With block variable not set.
I would like to finish the loop without ending up with the error as this has to be executed on multiple sheets. Here is the meat of the code:
'EmployerSummariesAddedForRegionsOnTabs Macro
Dim FoundCell As Range, LastCell As Range
Dim FirstAddr As String
With Range("D3:D3000")
Range("D3").Select
Set LastCell = .Cells(.Cells.Count)
End With
Set FoundCell = Range("D1:D3000").Find(What:=" Total", After:=LastCell, LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not FoundCell Is Nothing Then
FirstAddr = FoundCell.Address
End If
Do Until FoundCell Is Nothing
Set FoundCell = Range("D1:D3000").FindNext(After:=FoundCell)
COLUMNS("D:D").Select
Selection.Find(What:=" Total", After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Replace What:="Total", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
ActiveCell.Rows("1:1").EntireRow.Select
ActiveCell.Activate
Application.CutCopyMode = False
Selection.Insert Shift:=xlDown
ActiveCell.Offset(3, 0).Rows("1:1").EntireRow.Select
Selection.Insert Shift:=xlDown
.
.
.
If FoundCell.Address = FirstAddr Then
Exit Do
End If
Loop
Range("A1").Select
End Sub
There are two steps to creating an object variable. First you must declare the object variable.
this error occurs because you didn't set a object correctly it is quite the same as null refrence exception if you have programming experience.
I ran your code and it seems that it doesn't do anything at all! Not even an error! so I assume that your error must because of somewhere else in your code.
any way this lines replace any total in active worksheet with nothing:
Cells.Replace What:=" Total", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

If #REF! is found then Error Box Macro

I am trying to complete a simple macro that looks for '#REF!' in a worksheet due to a user alterting a row and ruining underlying formulas.
I have got as far as the find:
Sheets("Location_Multiple").Select
Range("A1:AL10000").Select
Selection.Find(What:="#REF!", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
From what I understand I need to enter an If parameter is true then
MsgBox"Please go back and check...."
Im just not sure what should follow the if....
Any pointers would be very much appreciated.
Try below code
Sub DisplayError()
On Error Resume Next
Dim rng As Range
Set rng = Sheets("Location_Multiple").Range("A1:AL10000")
Dim rngError As Range
Set rngError = rng.SpecialCells(xlCellTypeFormulas, xlErrors)
If Not rngError Is Nothing Then
For Each cell In rngError
MsgBox "Please go back and check.... " & cell.Address
Next
End If
End Sub
Use this, change the LookIn argument to xlValues instead of xlFormulas:
Selection.Find(What:="#REF!", After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
For a bit cleaner implementation:
Dim sht as Worksheet
Dim rngSrch as Range
Dim rngErr as Range
Set sht = Sheets("Location_Multiple")
Set rngSrch = sht.Range("A1:AL10000")
Set rngErr = rngSearch.Find(What:="#REF!", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not rngErr Is Nothing Then
'Do something to the offending cell, like, highlight it:
rngErr.Interior.ColorIndex = 39
End If
Anticipating there may be multiple cells with an error like this, you'll probably have to implement your .Find within a Do...While loop. There are several examples of that sort of problem on SO. If you have trouble implementing the loop, let me know.
The problem you have is because you're searching for a string - whereas #REF is an error.
You could use the IsError function, to return true for a cell with an error. Combine this with a loop, and you could achieve what you require. I haven't tested this, but you get the jist:
Set rng = Sheets("Location_Multiple").Range("A1:AL10000")
For Each cell In rngError
If IsError(cell) == true
MsgBox "Please go back and check.... " & cell.Address
Endif
Next

Reset Excel "Find and Replace" dialog box parameters

How do I programmatically reset the Excel Find and Replace dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?
I am using Application.FindFormat.Clear and Application.ReplaceFormat.Clear to reset find and replace cell formats.
Interestingly, after using expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords), the FindWhat string shows in the Find and Replace dialog box but not the ReplaceWhat parameter.
You can use this macro to reset find & replace. Unfortunately, you have to call them both as there are one or two arguments unique to each, so if you want to reset everything, you're stuck. There is no 'reset', so the only way I have found is to execute a fake find & replace using the default parameters.
Sub ResetFind()
Dim r As Range
On Error Resume Next 'just in case there is no active cell
Set r = ActiveCell
On Error Goto 0
Cells.Find what:="", _
After:=ActiveCell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False
Cells.Replace what:="", Replacement:="", ReplaceFormat:=False
If Not r Is Nothing Then r.Select
Set r = Nothing
End Sub
You can use the following command to open the "Replace" dialog with fields filled:
Application.Dialogs(xlDialogFormulaReplace).Show -arguments here-
the argument list is
find_text, replace_text, look_at, look_by, active_cell, match_case, match_byte
So far, the only way I've found to 'click' the buttons is with SendKey.
After much research and testing, I now know exactly what you want to do, but don't think it can be done (without SendKey). It appears that there is a bug in Excel, that won't reset the replacement value (from VBA), no matter what you try and set it to.
I did find this 'faster' way someone posted on MSDN, so you might give it a try.
Faster than Replace
No need to use sendkeys you can easily refer to the values you need to reset the dialog box values.
Sub ResetFindReplace()
'Resets the find/replace dialog box options
Dim r As Range
On Error Resume Next
Set r = Cells.Find(What:="", _
LookIn:=xlFormulas, _
SearchOrder:=xlRows, _
LookAt:=xlPart, _
MatchCase:=False)
On Error GoTo 0
'Reset the defaults
On Error Resume Next
Set r = Cells.Find(What:="", _
LookIn:=xlFormulas, _
SearchOrder:=xlRows, _
LookAt:=xlPart, _
MatchCase:=False)
On Error GoTo 0
End Sub
I tested this and it works. I have borrowed parts from a few places
Sub RR0() 'Replace Reset & Open dialog (specs: clear settings, search columns, match case)
'Dim r As RANGE 'not seem to need
'Set r = ActiveCell 'not seem to need
On Error Resume Next 'just in case there is no active cell
On Error GoTo 0
Application.FindFormat.Clear 'yes
Application.ReplaceFormat.Clear 'yes
Cells.find what:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext
Cells.Replace what:="", Replacement:="", ReplaceFormat:=False, MatchCase:=True 'format not seem to do anything
'Cells.Replace what:="", Replacement:="", ReplaceFormat:=False 'orig, wo matchcase not work unless put here - in replace
'If Not r Is Nothing Then r.Select 'not seem to need
'Set r = Nothing
'settings choices:
'match entire cell: LookAt:=xlWhole, or: LookAt:=xlPart,
'column or row: SearchOrder:=xlByColumns, or: SearchOrder:=xlByRows,
Application.CommandBars("Edit").Controls("Replace...").Execute 'YES WORKS
'Application.CommandBars("Edit").Controls("Find...").Execute 'YES same, easier to manipulate
'Application.CommandBars.FindControl(ID:=1849).Execute 'YES full find dialog
'PROBLEM: how to expand options?
'SendKeys ("%{T}") 'alt-T works the first time, want options to stay open
Application.EnableEvents = True 'EVENTS
End Sub
Dave Parillo's solution is very good but it does not reset the formatting options of Excel's Find an Replace dialog. The following is more thorough and does reset those options.
Sub ResetFindAndReplace()
Dim oldActive As Range, oldSelection As Range
On Error Resume Next ' just in case there is no active cell
Set oldActive = ActiveCell
Set oldSelection = Selection
On Error GoTo 0
Cells.Find what:="", _
After:=ActiveCell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False
Cells.Replace what:="", Replacement:="", ReplaceFormat:=False
Application.FindFormat.Clear
' return selection cell
If Not oldSelection Is Nothing Then oldSelection.Select
' return active cell
If Not oldActive Is Nothing Then oldActive.Activate
Set oldActive = Nothing
End Sub

Resources