If (search term) found, do (action). If not, end if - vba

If you guys could help me out, that would be great because it would really help me.
Here's what I'm trying to do:
Search for a cell with a specific term
If found, copy the entire row that the cell is in and paste it into a row above it.
If not found, do nothing and continue with the code
Here's my code:
Sub Test()
'
' Test Macro
'
' Keyboard Shortcut: Ctrl+b
'
Range("A5").Select
Cells.Find(What:="PL 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
If Not IsEmpty(ActiveCell.Value) Then
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A5").Select
ActiveSheet.Paste
End If
Range("A5").Select
Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
If Not IsEmpty(ActiveCell.Value) Then
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A6").Select
ActiveSheet.Paste
End If
Range("A5").Select
Cells.Find(What:="PL 3", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
If Not IsEmpty(ActiveCell.Value) Then
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A7").Select
ActiveSheet.Paste
End If
End Sub
My code only works if the value is found. If it's not found it runs into the error below:

Cells.Find is a function that returns a Range object reference; when it doesn't find anything, the reference will be Nothing. And you can't call .Activate on Nothing:
This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell. (MSDN)
Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
You need to rewrite your code and avoid .Select and .Activate, and avoid working with ActiveCell and implicitly with ActiveSheet (which you are doing by not qualifying the Cells call with a proper worksheet reference).
Your formatting makes it hard to read the code, for several reasons:
Arguments are being specified on different lines
Line continuations are being palced at arbitrary locations
Nested member calls aren't lined up
Compare to:
Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) _
.Activate
That's just readability. The problem is that you basically assume that .Find returns a valid object reference. Don't assume, explicitly check:
Set result = Cells.Find(...)
If Not result Is Nothing Then result.Activate
But really, you need to figure out a way to avoid .Select and .Activate.

You can try something like this instead (untested):
Sub HideAndSeek()
Dim foundCell As Range
For i = 1 To 3
Set foundCell = Cells.Find(What:="PL " & i, LookIn:=xlFormulas, LookAt:=xlPart)
If Not foundCell Is Nothing Then
Intersect(foundCell.EntireRow, ActiveSheet.UsedRange).Offset(-1, 0).Value = _
Intersect(foundCell.EntireRow, ActiveSheet.UsedRange).Value
End If
Set foundCell = Nothing
Next
End Sub
The principle being that you write the code you need once and then create a loop to repeat the code for you.
The other part of this answer is checking that the cell was found - to do this we check that the range was actually set (which means it isn't Nothing) using
If Not foundRange Is Nothing

Related

How to use the find funtion to search for the Value of a text box?

I am trying to make a userform that can bring up data using an ID number.
I am trying to reference a text box and select it, and then using it as a reference to fill out the Time and comments in the sheet. I think the is I cant put "txtID.Value" into the Find function.
Here is an example of my code:
Sheet1.Select
Columns("A:A").Select
Selection.Find(What:="txtID.Value", After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
ActiveCell.Offset(0, 8).Value = txtTime2
ActiveCell.Offset(0, 9).Value = txtComment2
When using the Find function, it's recommended to use a Range object, and set it to the result. This method allows you to trap a possible scenario where Find failed to find a match in the searched range Sheet1.Columns("A:A").
Also, try to avoid using Select, Selection and ActiveCell, and use fully qualified Range objects (like in the code below).
Code
Dim FndRng As Range
Set FndRng = Sheet1.Columns("A:A").Find(What:=txtID.Value, LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not FndRng Is Nothing Then ' successful find
FndRng.Offset(, 8).Value = txtTime2
FndRng.Offset(, 9).Value = txtComment2
Else ' unable to fins the value in txtID
MsgBox "Unable to find " & txtID.Value & " in Sheet1"
End If
Note: if you have this code outisde the User_Form module, then you need to add the User_Form reference when trying to get the txtID.Value.
For eaxmple, let's say the name of your form is UserForm1, then change this line to:
Set FndRng = Sheet1.Columns("A:A").Find(What:=UserForm1.txtID.Value, LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
To Make it work, you will have to put the code as below, which is quite self explainatory.
Selection.Find(What:=Userform1.textbox1.value, After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
hope this helps

VBA Copy & Find

I have hunted online and not yet managed to find anything to covers what I need.
Hopefully this will make sense.
I need to copy the current cell, select sheet2, then find the string in that sheet.
I'm sure it's a simple bit of code and I have got it to the point where I can find the text, but only when I put it directly into the code. I just need it to use the current cell.
Sub Find()
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select
Cells.Find(What:="MYDATA", After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
End Sub
All help is gratefully received.
Thanks.
Modified your code to include the value of the current cell as a variable findValue and then using that as the what argument in the find function.
Try this out:
Sub Find()
findValue = ActiveCell.Value
Sheets("Sheet2").Select
Range("A1").Select
Cells.Find(What:=findValue, After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
End Sub

Getting run-time error running VBA code not my own

I need to reverse engineer someone else's code and make it run. Right now it is throwing an error at me complaining that some variable isn't set.
I'm not sure what it is talking about exactly. Here is the top part of the subroutine with the error.
Sub OBI_Vendor_Detail_Macro()
Cells.Select
With Selection
.WrapText = False
.MergeCells = False
End With
Range("C4").Select
Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
The last line produces this error Run-time error '91': Object variable or With block variable not set
Hope I've provided enough info. If not please let me know. Thanks.
You need to try to Find first, then check that you found something:
Dim foundCell As Range
Set foundCell = Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
foundCell.Activate
End If

Looking for multiple terms (sorted by priority)

Would it be possible to use the find method to search for back-up options?
Here's my code right now:
Set foundCell = Cells.Find(What:="RCP 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
If Not foundCell Is Nothing Then
foundCell.Activate
foundCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A" & (PLcount + 8)).Select
ActiveSheet.Paste
Else
Set foundCell = Cells.Find(What:="RCP- 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
If Not foundCell Is Nothing Then
foundCell.Activate
foundCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A" & (PLcount + 8)).Select
ActiveSheet.Paste
End If
End If
I would like to be able to do something like below. Note the text after .Find(What:=)
Set foundCell = Cells.Find(What:="RCP 1" "RCP- 1" "RCP 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
If Not foundCell Is Nothing Then
foundCell.Activate
foundCell.Rows("1:1").EntireRow.Select
Selection.Copy
Range("A" & (PLcount + 8)).Select
ActiveSheet.Paste
End If
Where the first term is the first priority, the second term is the second priority, the third term is the third priority, etc.
EDIT - there is only limited support for wildcards in Find() - you would probably not class it as "regex-level" functionality:
* - zero or more characters
? - single character
~ - escapes * or ? if you want to find those literal characters
Alternatively can put the Find into a separate function:
Sub Tester()
Dim foundCell, PLCount As Long
PLCount = 3
Set foundCell = FindFirst(Cells, Array("RCP 1", "RCP- 1"))
If Not foundCell Is Nothing Then
'no need for any select/activate
foundCell.EntireRow.Copy Destination:=Range("A" & (PLCount + 8))
End If
End Sub
'return the first match to a value in the array "arrWhat"
' Returns Nothing if no match
Function FindFirst(rngWhere, arrWhat) As Range
Dim v, f As Range
For Each v In arrWhat
Set f = rngWhere.Find(what:=v, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not f Is Nothing Then Exit For
Next v
Set FindFirst = f
End Function

need be more dynamic when using search function in vba

I have the following code and is stuck when wondering how to make the search result more dynamic, that is after searching the "price", i need to copy the "price" and the cell at the right of it to cell A1, any help is appreciated.
Sub Macro1()
Cells.Find(What:="price", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
Range("L14:M14").Select
Selection.Copy
Range("A1").Select
ActiveSheet.Paste
Range("A1").Select
End Sub
Sub Macro1()
Dim f as Range
Set f = Activesheet.Cells.Find(What:="price", After:=ActiveCell, _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:= False, SearchFormat:=False
if not f is nothing then
f.resize(1,2).copy Activesheet.Range("a1")
end if
End Sub