I am working making a primary sheet that retrieves data from other sheets automatically based on entries in certain cells using macros. My main sheet lists tasks, and my secondary sheet lists responsible party metadata (contact info, etc.). If a responsible party value is entered in a particular column in the main sheet, the macro searches the appropriate column in the second sheet, and if it finds it, copies all the data in the row and pastes it next to the entered value in the first sheet. It works to successfully retrieve the data from the first match it finds, but for some items there can be multiple matches. I need the code to retrieve all matches, insert new rows for each, and group them. Here is my code so far:
Is this reasonably viable? Thanks in advance for any help you can offer.
Code:
Sub Populate_System_Details()
Dim WB As Workbook
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Dim x As String
Dim y As String
Dim WS1Range As Range
Dim lastrow As Long
Set WB = ActiveWorkbook
Set WS1 = WB.Worksheets("Main")
Set WS2 = WB.Worksheets("Sys_ref")
lastrow = WS2.Range("A65536").End(xlUp).Row
Set WS1Range = Range("F2:F" & lastrow)
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
'apply function to all cells in the F column
For Each cell In WS1Range
'get the selected cell's value
y = cell.Value
'get the selected cell's location
x = cell.Address
'if the cell is not blank, search for the value in second sheet
If Not y = "" Then
'find value in second sheet
Set records = WS2.Range("B2:B" & lastrow).Find(y)
'make sure second sheet is active
Sheets("Sys_ref").Select
'select the cell immediately to the right of cell where y value is found
Sheets("Sys_ref").Range(records.Address(RowAbsolute:=False, ColumnAbsolute:=False)).Offset(0, 1).Select
'from cell selected above, select all cells to the right with contents
Range(Selection, Selection.End(xlToRight)).Select
'copy the selection
Selection.Copy
'set first sheet as active
Sheets("Main").Select
'paste the copied data one cell to the right of the entered value
ActiveSheet.Paste Destination:=WS1.Range(x).Offset(0, 1)
End If
'clear all cells to the right if the cell is blank
If y = "" Then
Sheets("Main").Select
Sheets("Main").Range(x).Offset(0, 1).Select
Range(Selection, Selection.End(xlToRight)).ClearContents
End If
Next cell
Application.ScreenUpdating = True
ErrorHandler:
Select Case Err.Number
'Common error: the specified text wasn't in the target worksheet.
Case 9, 91
Application.ScreenUpdating = True
MsgBox "The value " & y & " was not found in Sys_ref"
Exit Sub
'General case: turn screenupdating back on, and exit.
Case Else
Application.ScreenUpdating = True
Exit Sub
End Select
End Sub
Is this reasonably viable? Thanks in advance for any help you can offer.