Excel run-time error 91, without object variable - vba

I'm receiving a Run-time Error '91' Object Variable or With Block not Set for the following code.
I'm confused as I'm not using any object variables (I don't think, I'm new to VBA). Debugging highlights the 6th row.
My code is:
Dim i As Integer
i = 1
Columns("A:A").Select
Selection.Find(What:="" & Cells(i, 19).Value, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
MsgBox ActiveCell.Row

I'm receiving a Run-time Error '91' Object Variable or With Block not Set for the following code.
When working with .Find, check if a match was returned and then show the row if found else you will get the above error.
Try this
Option Explicit
Sub Sample()
Dim i As Integer
Dim aCell As Range
Dim ws As Worksheet
i = 1
'~~> Replace this with the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
Set aCell = .Columns(1).Find(What:=.Cells(i, 19).Value, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
'~~> Check if the find returned a match
If Not aCell Is Nothing Then
MsgBox aCell.Row
Else
MsgBox "Not Found"
End If
End With
End Sub

Related

VBA Do (delete column where find is true) Until Find is False then exit do

I have an excel file that has the text "Income from Trans" where I will need to delete the entire column.
This is my current code in VBA 2010 that works until there are no more cells with "Income from Trans"; I can't get it to break out of the loop.
Any idea why?
Dim rng1 As Range
Dim target1 As String
target1 = "Income From Trans"
Set rng1 = Cells.Find(What:=target1, _
After:=ActiveCell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
Do Until rng1 Is Nothing
Cells.Find(What:=target1, After:=ActiveCell, _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows,
SearchDirection _
:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.EntireColumn.Delete
Loop
Your code Set rng1 = Cells.Find... will set rng1 to be a range object, assuming it finds your value. Next is your loop which will ultimately cause rng1 to be deleted. It continues to loop because even though rng1 is deleted it still was assigned and therefore isn't Nothing. It ends with an run time error message of 91 because rng1 was set but deleted. You can see in the locals window View>Locals Window that its type is still Range\Range even though it's actually been deleted.
You have implicit cell references from the unqualified Cells usage. That means this code will run on whatever worksheet happens to be the ActiveSheet. Implicit references can have unintended side effects when you don't realize this. It's best to fully qualify them so there's no ambiguity as to which sheet they reside on. I'm assuming ActiveCell falls into this category too since you want it to wrap delete until there "Income from Trans" is no longer found.
The code .Activate followed by ActiveCell. isn't needed and can be shortened by removing both so it ends up as SearchFormat:=False).EntireColum.... Selecting a range object isn't usually necessary. Joining the two makes it apparent what you're doing.
Below you'll find a simpler version that uses .Find is in your original to find the first instance. After that it uses .FindNext() to continue looping until all are found. This eventually exits because it is setting the range variable found after every deletion, ultimately leaving found as Nothing after it's deleted the last. The RemoveColumns has parameters which allow you to use this on more than just a single sheet.
Sub Test()
RemoveColumns Sheet1, "Income From Trans"
End Sub
Sub RemoveColumns(ByVal sheetToSearch As Worksheet, ByVal value As String)
Dim found As Range
Set found = sheetToSearch.Cells.Find(What:=value, After:=sheetToSearch.Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
Do Until found Is Nothing
found.EntireColumn.Delete
Set found = sheetToSearch.Cells.FindNext
Loop
End Sub
Check the search result inside the loop as well
Dim rng1 As Range, target1 As String, firstFound As String
target1 = "Income From Trans"
Set rng1 = Cells.Find(What:=target1, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False)
If Not rng1 Is Nothing Then
Do
firstFound = rng1.Address
Set rng1 = Cells.Find(What:=target1, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
If Not rng1 Is Nothing Then rng1.EntireColumn.Delete
Loop While Not rng1 Is Nothing And rng1.Address <> firstFound
End If

Searching for a value from a specific cell on another sheet

I am using userforms to input data, at a certain point part of the data is copied to one of the sheets in the workbook.
My code then needs to use one of the values in the sheet to check if this value apears on another sheet, if it does it copies values linked to that value to the original sheet and then populates the userform so that further info can be captured.
If I activate on error resume next everything works except the tab function stops working on the userform, if I run it without on error resume next, I get run-time error:
'91' Object variable or with block variable not set.
How do i fix this?
Sub Find_7_day()
Dim vfind
Dim rng As Range
Sheets("Test Data").Select
Sheets("Test Data").Range("$E$3").Select
vfind = ActiveCell
'On Error Resume Next
Call Sheet
Set rng = Cells.Find(What:=vfind, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
If ActiveCell = vfind Then
Call Old_7_day
Call Form_7_day_fill
Else
Sheets("Test Data").Select
End If
End Sub
You can't declare and .Activate a variable range at the same time:
Dim rng As Range
Set rng = Cells.Find(What:=vfind, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
suggestion, avoid using .Select and Activate, explanation here How to Avoid the Select Method in VBA & Why
Code:
Sub Find_7_day()
Dim vfind As String
Dim rng As Range
vfind = Sheets("Test Data").Range("$E$3").Value
Call Sheet
Set rng = Cells.Find(What:=vfind, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=True, _
SearchFormat:=False)
If rng Is Nothing Then
MsgBox vfind & " " & "dont exist"
Exit Sub
End If
If rng.Value = vfind Then
Call Old_7_day
Call Form_7_day_fill
Else
Sheets("Test Data").Select
End If
Exit Sub
End Sub

find a cell with specific text, multiple occurences, and past active cell in all cells containing specific text

I am currently working on a report, originating in Infoview (SAP business Objects)
This is a report that provides valuable information on a weekly basis, to enhance awareness of current shop performance.
Like the tile of the post might show i want to find a cell with specific text. It has multiple occurrences, and I want to past a previously selected cell in all of those instances.
I can reach the same result by Ctrl-F, "Search all" ( for the "specific text") and than Paste (the previously selected cell)
( http://www.extendoffice.com/documents/excel/816-excel-select-cells-with-specific-text.html)
But i would like to automate this.
I want to use:
Cells.Find(What:="[ö]", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
and
Cells.FindNext(After:=ActiveCell).Activate
But I can't incorporate the two in one macro that gives me the result i describes above.
The previously selected cell contains a formula, containing index(match) and a reference to a cell on the same row as the "specific text".
In my opinion this way of doing stuff saves me a lot of trouble with dynamic cell references ect.
I hope you can help
Your request is a little vague, but I believe this will get you started
Dim PasteValue as string 'this is what you're pasting in
Dim WS as Worksheet
Dim FirstCell as string
Dim rng as range
PasteValue = 'do something here to get your value
set rng = Cells.Find(What:="[ö]", LookIn:=xlFormulas, LookAt:= xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
while not rng is nothing 'make sure you found something
if len(FirstCell) = 0 then
firstcell = rng.address 'save this spot off so we don't keep looping
end if
rng.value = PasteValue
'now find the next one
set rng = Cells.Find(What:="[ö]", LookIn:=xlFormulas, LookAt:= xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
if rng.address = FirstCell then 'back at the first cell
set rng = nothing 'so get out of the loop
endif
end while
Thanks for the code above, it helped a lot.
This is the final code, in case anyone needs it. The
If rng Is Nothing Then Exit Do
Loop While rng.Address <> strFirstAddress
is particulary usefull.
Sub Fill_VCNC()
Dim formula_ö As String
Dim rng As Range
Dim strFirstAddress As String
With Range("S:S")
Set rng = Cells.Find(What:="[ö]", LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
If Not rng Is Nothing Then
strFirstAddress = rng.Address
Do
rng.formula = formula_ö
.NumberFormat = "0.00"
Set rng = .FindNext(rng)
If rng Is Nothing Then Exit Do
Loop While rng.Address <> strFirstAddress
End If
End With
End Sub
( source : https://social.msdn.microsoft.com/Forums/en-US/958fca4e-b19d-4b50-8235-e05adc7f25d5/loop-through-a-range-until-value-not-found?forum=exceldev)

With Sheets("").Range("B:B"); Variable range when searching

Here´s the thing, I have a code that uses a fixed range in a fixed sheet to search for a value. I need now to make the sheet variable. I´ve tried couple of things with no luck so far.
The name of the sheet where I need to search is determined by a cell in another sheet. Replacing the 3rd line with something like: "With Sheets("Sheets("asd").range("A1")").Range("B:B") does not work.
My code:
FindString = W
If Trim(FindString) <> "" Then
With Sheets(**"CARS"**).Range("B:B")
Set Rng = Cells.Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
End If
Let me know if more info is required.
Thanks!
Try omitting some of the doublequotes: With Sheets(Sheets("asd").range("A1")).Range("B:B")
Explanation
When you do this, you'll get a compile error: Expected list separator or ):
With Sheets("Sheets("asd").range("A1")").Range("B:B")
This is because the double-quotes encapsulate a string literal, so in this case the string literal is "Sheets(", which raises an error at asd (and subsequent errors, too).
The solution is to simply refer to the Sheets("asd") object, there is no need to qualify that object within quotes :)
NOTE Brad identifies another potential error in your code, see his answer below.
replace "With Sheets("Sheets("asd").range("A1")").Range("B:B")
by:
dim VAR_Sheet as string
Var_Sheet=Sheets("asd").range("A1").value
With Sheets(Var_Sheet).Range("B:B")
...code...
end with
works also like this (same result):
With Sheets(Sheets("asd").range("A1").value).Range("B:B") 'removed quotes that made error
It looks like, while you types With you are actually not using it.
With Sheets("CARS").Range("B:B")
Set Rng = Cells.Find(What:=FindString, _ <~~ Cells references the active sheet
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
You need to start the statement with a dot to signify you are continuing the reference established int eh With
With Sheets("CARS").Range("B:B")
Set Rng = .Find(What:=FindString, _ <~~ .Cells
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
I assume the double * was for emphasis (Sheets(**"CARS"**) --> Sheets("CARS"))

excel macro cells.find won't use variable for some reason

I have this code as an excel macro.
Dim MyData As DataObject
Set MyData = New DataObject
MyData.GetFromClipboard
MsgBox MyData.GetText
On Error GoTo NotFound
Cells.Find(What:=MyData.GetText, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
NotFound:
MsgBox writes the value correctly, but the What:=MyData.GetText just won't work. Why? Or, more importantly, how to fix it?
If it is not clear, I am trying to find the next value equal to the one in clipboard at the moment. I have referenced the MSForms so that is not the problem.
If I assign MyData.GetText to a variable and use the variable, the same happens, MsgBox works, BUT What:=myvariable doesn't.
Not sure why this works, but it does:
Sub test()
Dim MyData As DataObject
Dim rng As Excel.Range
Set MyData = New DataObject
MyData.GetFromClipboard
Set rng = ActiveSheet.Cells.Find(What:=MyData.GetText, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
rng.Activate
End Sub