I am having an issue with this function searching for a Column header than using the column number as the reference for searching in a different sheet.
Sub Search(COL_TITLE As Variant, BOMSheet As Worksheet, prompt As String)
Dim wb As Workbook, ws As Worksheet, found As Range
Dim wbSearch As Workbook, wsSearch As Worksheet
Dim rng As Range, iResultCol As Integer, iPartCol As Integer
Set wb = ThisWorkbook
Set ws = BOMSheet
' headers
Set rng = ws.UsedRange.Rows(1)
' determine part number col
Set found = rng.Find(COL_TITLE, , xlValues, xlPart)
If found Is Nothing Then
MsgBox "Can't find "& COL_TITLE, vbCritical, "Search failed"
Exit Sub
End If
iPartCol = found.Column
' determine last col
iResultCol = rng.Columns.count + rng.Column
ws.Cells(1, iResultCol) = prompt & " Search Result"
Debug.Print rng.Address, iPartCol, iResultCol
Dim sFilename As String
sFilename = Application.GetOpenFilename(Title:=prompt, FileFilter:="Excel Files (*.xls*),*xls*")
If Len(sFilename) > 0 Then
Set wbSearch = Application.Workbooks.Open(sFilename)
Else
MsgBox "No file chosen", vbExclamation
Exit Sub
End If
' find last row
Dim iLastRow As Long, iRow As Long, sPartNo As String, count As Long
iLastRow = ws.Cells(Rows.count, iPartCol).End(xlUp).Row
Debug.Print "iLastRow", iLastRow
' search each sheet
For Each wsSearch In wbSearch.Sheets
For iRow = 2 To iLastRow
sPartNo = ws.Cells(iRow, iPartCol)
If Len(sPartNo) > 0 Then
Set found = wsSearch.UsedRange.Find(sPartNo, , xlValues, xlWhole)
If found Is Nothing Then
' not found
Else
ws.Cells(iRow, iResultCol) = "Found in "& wbSearch.Name & _
""& wsSearch.Name & _
" at "& found.Address
count = count + 1
End If
End If
Next
Next
' end
wbSearch.Close False
MsgBox count & " matches", vbInformation, "Finished"
End Sub
I am calling this function twice. The first time the call is:
Call Search("Part Number", BOMSheet, "Choose OCCL File")
This one works perfectly but in the second call:
Call Search("Manfacturer PN", BOMSheet, "Choose OCCL File")
The exit sub message is given, so I think the function isn't finding the column with the header "Manufacturer PN". I don't see anything wrong here and I am not getting any errors so I am kind of stuck. Code courtesy of CDP1802.
Here's the sheet with the headers for reference: Snip from Sheet