VBA Copy & Find - vba

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

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

Searching and Selecting multiple data in Worksheets w/ common header

I just started using VBA for making my life easier, programming is not my background at all. When I run codes I may write too much.
So I have two questions, check the code below.
Sub Find()
'
' Find Macro
'
'
'L.NAM.O
Worksheets("LAC").Select
Cells.Select
Selection.Find(What:="forecast_quarter", After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("NewForecast").Select
Range("K2").Select
ActiveSheet.Paste
'L.NAM.M
Worksheets("EMEA").Select
Cells.Select
Selection.Find(What:="forecast_quarter", After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("NewForecast").Select
Range("K" & Rows.Count).End(xlUp).Offset(1).Select
ActiveSheet.Paste
I want to be able to find the forecast_quarter in both sheets(I have 3 in total) and paste in one Worksheet(New Forecast), one below other. The thing is, I think this is too much, might have an easier way than run all the process all over again.
My idea would be, "search the forecast_quarter quarter in the worksheets I want and paste on below the other). As I have all criterias to do that, this could me massive. Any easier, better way to run it?
Thanks!
Something like this (untested) should work.
Sub CopyAll()
CopyDataByHeader "LAC", "forecast_quarter"
CopyDataByHeader "EMEA", "forecast_quarter"
End Sub
'Look for a specific header on a sheet, and if found copy
' the data below it to "NewForecast" sheet
Sub CopyDataByHeader(shtName As String, hdrText As String)
Dim f As Range
With ActiveWorkbook.Sheets(shtName)
'search for the header
Set f = .Cells.Find(What:=hdrText, After:=.Cells(1), _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not f Is Nothing Then
'found the header: copy the data below it
.Range(f.Offset(1, 0), .Cells(.Rows.Count, f.Column).End(xlUp)).Copy _
ActiveWorkbook.Sheets("NewForecast").Cells( _
Rows.Count, "K").End(xlUp).Offset(1, 0)
Else
'header not found...
MsgBox "Header text '" & hdrText & "' not found on sheet '" & shtName & "' !"
End If
End With
End Sub

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

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

Excel VBA find #N/A

I have a worksheet with a formula that returns =NA() under certain conditions. Using VBA, I'd like to find #N/A, but I haven't been able to tweak this answer.
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
I've tried What:=CVErr(xlErrNA), What:=xlErrNA and also What:="#N/A" to no avail.
As an added difficulty, I have to take Dutch into account, so What:="#N/A" probably wouldn't even work in Dutch.
Note. I'm asking this question out of curiosity as I haven't found a method online.
At this moment, I'm calculating which cells contain =NA()
You're looking in the cell formulas. Try looking in the cell values, then I can get this to work using the string "#N/A" for the What argument:
lastrow = .Cells.Find(What:="#N/A", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Please try the below code ,
You should use the loop to read the error.
Sub Test()
If Range("A2").Text = "#N/A" Then
MsgBox "hi"
End If
End Sub
Hi I have another solution,
You have paste these formulas values into another columns as text and
then use the replace code,
Please try the below code.
Sub Tst()
Columns("C:C").Select
Selection.Copy
Range("D1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Replace What:="#N/A", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
The column C Contains formulas values (Error) .
The problem here is that you're looking for "#N/A" as a value of the cell and it's not the value it's a error indicator, so if you're trying to find a cell wich gives you a error you have to use something like this:
If WorksheetFunction.IfError("Put here a loop to read the cells;"Error")="Error" then
"Write what you desire for cells with error"
end if

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