Searching for cell value in a different excel workbook - excel

I have a Excel workbook (lets call serial_numbers) that contains a list of S/N on A1 to A10 (can be more or less).
Now I have to search for A1's value on workbook "database". That value is usually found in A1 cell of workbook "database".
In case that I find A1's valueI need to copy and paste B2's value of workbook "database", which cointains the current stock of that value.
Through Developer mode on Excel I got the following result:
Sub Macro1()
'
' Check stock for S/N in database
'
'
Range("A1").Select
Selection.Copy
Workbooks.Open Filename:="database.xlsx", _
UpdateLinks:=0
Range("A1").Select
Selection.Find(What:="XXXXXX", After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range("B1").Select
Application.CutCopyMode = False
Selection.Copy
Windows("serial_numbers.xlsx").Activate
Range("B1").Select
ActiveSheet.Paste
End Sub
That piece above seems to be not working properly and since Im new to this I cant get why. Can any of you help me?

If you are looking for non-vba solution then you may go for vlookup function.
Try this code :
Sub testMacro()
Dim wkbDB As Workbook
Dim rngFind As Range, rngSearch As Range, cell As Range
Dim shtDB As Worksheet
Set wkbDB = Workbooks.Open(Filename:="C:\database.xlsx", UpdateLinks:=0)
Set shtDB = wkbDB.Sheets("Sheet1")
Set rngSearch = ThisWorkbook.Sheets("Sheet1").Range("A1:A10")
For Each cell In rngSearch
Set rngFind = shtDB.Range("A1:A10").Find(What:=cell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows)
If Not rngFind Is Nothing Then
'serial_numbers.xlsx
cell.Offset(0, 1) = rngFind.Offset(0, 1)
End If
Next
End Sub

Related

Using the value of one cell to locate another on a different sheet

I'm trying to get a VBA code together that can take the date from cell B5 on one sheet and locate the exact match from a column on a different sheet, then select that as the active cell. any ideas?
Heres what i've tried;
Sub find()
Sheets("Details").Select
Range("B5").Select
rngY = ActiveCell.Value
Sheets("Calcs").Select
Columns("C:C").Select
Selection.find(What:=rngY, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
End Sub
Something like this should work for you:
Public Sub FindInSheet2()
Dim r As Range, lookupVal As Variant
lookupVal = ThisWorkbook.Worksheets("Details").Range("B5").Value
Set r = ThisWorkbook.Worksheets("Calcs").Range("C:C").Find(What:=lookupVal, LookAt:=xlWhole, LookIn:=xlValues)
If Not r Is Nothing Then
ThisWorkbook.Worksheets("Calcs").Activate
r.Select
Else
MsgBox "Lookup not found", vbOKOnly
End If
End Sub
The main difference between this code and yours is that I haven't relied on ActiveCell or Selection. It's better to be specific about which ranges you are working with. For more info, see How to avoid using Select in Excel VBA

How to loop through a range of cells?

I have values in this "Sample Analysis Data" sheet in the range B2:B10.
For each cell in the range, the code looks for that value in the sheet "Meta Data". It then copies the cells in that row and pastes it in "Sample Analysis Data" (to the right of the searched value). This works for the value in B2.
I can't get it to move on to B3 and then B4 and such. It loops though and does the same thing again for B2.
What do I need to do to get it to loop to from B2 through to B10?
Along with this, how do I get it to go from B2 to the last entry in the column (as each data set I work with could have a different number of rows of data,) not just to B10?
Sub GetMetaData()
Worksheets("Sample Analysis Data").Activate
Range("B2").Select
Dim srch As Range, cell As Variant
Set srch = Range("B2:B10")
For Each cell In srch
Sheets("Meta Data").Activate
Cells.Find(What:=cell, LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
ActiveSheet.Cells(ActiveCell.Row, 1).Select
Range(ActiveCell, ActiveCell.End(xlToRight).End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sample Analysis Data").Activate
ActiveCell.Offset(0, 7).Select
ActiveSheet.Paste
Next cell
End Sub
Try this?
Change the i=8 to however many cells you need to offset (you indicated B2:B10, which is 8)
Sub testcopy()
Dim srch As Range, metarg As Range, rg As Range, pstrg As Range
Dim i As Long
Dim ws As Worksheet, ws2 As Worksheet
Set ws = ThisWorkbook.Sheets("Sample Analysis Data")
Set ws2 = ThisWorkbook.Sheets("Meta Data")
Set metarg = ws2.Range("A1:A100") 'range that includes the key that you are searching in B2:B10
Set srch = ws.Range("B1") 'i'm offsetting, so i'm going back one row
For i = 1 To 8 'change 8 to how many cells to offset
Set rg = metarg.Find(srch.Offset(i, 0).Value, LookIn:=xlValues, lookat:=xlWhole) 'find the value in meta sheet
If Not rg Is Nothing Then
Set pstrg = ws2.Range(rg, ws2.Cells(rg.Row, rg.End(xlToRight).Column))
pstrg.Copy
srch.Offset(i, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End If
Next i
End Sub

Search a copied value MACRO

I have two sheets:
Database
Macro sheet: It has a row with dates that will be the headings of a table after the macro.
Objective: In the macro sheet take the value of the first date and look for its position in the database sheet. Then, in the database sheet, copy the entire column corresponding to the previously copied date.
I understand that the code should look something like this:
Sheets("Macro").Select
Range("K3").Select
Selection.Copy
Sheets("Database").Select
Cells.Find(What:=Selection.PasteSpecial xlValues, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Macro").Select
ActiveSheet.Paste
This code does not work, because the search part is not done well, I will appreciate some correction
Something along these lines.
Read this to learn the advantages of not using Select or Activate.
When using Find, always check first that your search term is found to avoid an error. For example, you cannot activate a cell that does not exist.
Sub x()
Dim r As Range
With Sheets("Database")
Set r = .Cells.Find(What:=Sheets("Macro").Range("K3").Value, lookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not r Is Nothing Then
Range(r, r.End(xlDown)).Copy Sheets("Macro").Range("A1")
End If
End With
End Sub
Loop through he header dates in the Macro worksheet. If any can be found in the header row of the Database worksheet, copy that column to the Macro worksheet under the header.
sub getDateData()
dim h as long, wsdb as worksheet, m as variant, arr as variant
set wsdb = worksheets("database")
with worksheets("macro")
for h=1 to .cells(1, .columns.count).end(xltoleft).column
m = application.match(.cells(1, h).value2, wsdb.rows(1), 0)
if not iserror(m) then
arr = wsdb.range(wsdb.cells(2, m), wsdb.cells(rows.count, m).end(xlup)).value
.cells(2, h).resize(ubound(arr, 1), ubound(arr, 2)) = arr
end if
next h
end with
end sub

Find a value in range + loop

I need my macro to Look at a cell in my range, Find that value in the a different WS and paste a value on to that's next to the value i'm looking for (my original WS). do this again and again to the values in the range.
now it all works but for some reason the value is stuck on the first search and wont look for other values in the original range.
here is my code, and the pictures should help.
Sub Macro1()
'
'now im gonna match the "UDD" TO THE "S/O"
Worksheets("Sheet1").Activate
Range("c17").Select
Dim Searchkey As Range, cell As Range
Set Searchkey = Range("c17:c160")
For Each cell In Searchkey
Sheets("data").Activate
Cells.Find(What:=Searchkey, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
ActiveCell.Offset(0, -1).Range("A1").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Activate
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveSheet.Paste
ActiveCell.Offset(1, -1).Range("A1").Select
Selection.Copy
Next cell
End Sub
why is my macro stuck on "84225" and not looping to the other S/O?
Thank you
Sub mac1()
Worksheets("Sheet1").Activate
Range("c17").Select
Dim srch As Range, cell As Variant
Set srch = Range("c17:c160")
For Each cell In srch
Sheets("data").Activate
Cells.Find(What:=cell, LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
ActiveCell.Offset(0, -1).Range("A1").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Activate
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveSheet.Paste
ActiveCell.Offset(1, -1).Range("A1").Select
Selection.Copy
Next cell
End Sub
this is working!
thank you all
On each loop you're searching for the whole range of SearchKey and not just Cell so I'm guessing it's always using the first cell in SearchKey as your search criteria.
You're also searching in the formula rather than the values, and looking for a part match which may return incorrect results (part match on 20 would return a find in 20, 201, 11120001, etc).
Not qualifying your sheet names and using Activate probably isn't helping much either.
Try this code:
Public Sub Test()
Dim SrcSht As Worksheet, TgtSht As Worksheet
Dim SearchKey As Range, Cell As Range
Dim FoundValue As Range
With ThisWorkbook
Set SrcSht = .Worksheets("Sheet1")
Set TgtSht = .Worksheets("Data")
End With
Set SearchKey = SrcSht.Range("C17:C21")
For Each Cell In SearchKey
'Search column 3 (C) for your the value
Set FoundValue = TgtSht.Columns(3).Find(What:=Cell, _
After:=TgtSht.Columns(3).Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
'Only proceed if value found, otherwise an error will occur.
If Not FoundValue Is Nothing Then
Cell.Offset(, 1) = FoundValue.Offset(, 1)
End If
Next Cell
End Sub
Edit:
To test the code place the cursor within the procedure and press F8 to process each line in turn. The FoundValue should contain a value each time it's executed.
To check this hover your cursor over the variable to see its value:
The row highlighted in yellow is the next line that will be executed. If FoundValue is nothing then the following line isn't processed, if it's not nothing then the line is executed.

vba excel 2003 copy range find and paste the selected range

I am trying to write a macro in excel sheet. In this macro, do I take a copy of the cell number (B04) and I search on the worksheet (3), but the problem that I am having is when I want to change the content of the cell macro is also searching for new content
Range("D6").Select
Selection.Copy
Sheets("3").Select
Cells.Find(What:="Yasser Arafat Ateya ELsayed EL", After:=ActiveCell, _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Range("B6").Select
Application.CutCopyMode = False
Selection.ShowDetail = True
End Sub
Going with the flow of your code, and with a bit of explanation to help you, amend your code to something like this. Also learn about explicitly referencing separate worksheets in your code rather than relying on ActiveSheet.
Sub findSomeText()
'the find method returns a Range so define a variable to catch this
Dim fndrng As Range
'to search for different strings use a String variable
Dim srchStr As String
'get the srchStr (in this case from D6 in the ActiveSheet)
srchStr = ActiveSheet.Range("D6").Value
'use Sheets("3") - you don't need to select it
'note that this means a Sheet with a (Tab)NAME of "3", not necessarily the third sheet
With Sheets("3")
'explicitly set the ActiveCell to Find from
Range("A1").Activate
'apply the Find method, note use LookIn:=xlValues; use of srchStr and .Cells
Set fndrng = .Cells.Find(What:=srchStr, After:=ActiveCell, _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
'check if a match has been found
If Not fndrng Is Nothing Then
'your code if srchStr has been found goes here e.g. found value into cell B6
Range("B6").Value = fndrng.Value
' perhaps use MsgBox "Found" to test?
Else
'your code if srchStr has NOT been found goes here
MsgBox "Not Found"
End If
End Sub

Resources