Sub MatchAndCopyValues()
Dim wsAT&T As Worksheet
Dim wsHR As Worksheet
Dim lastRowAT&T As Long
Dim lastRowHR As Long
Dim i As Long, j As Long
Dim deptCode As Variant
' Find the sheet starting with "AT&T"
For Each wsAT&T In ThisWorkbook.Worksheets
If Left(wsAT&T.Name, 4) = "AT&T" Then
Exit For
End If
Next wsAT&T
' Set the HR worksheet
Set wsHR = ThisWorkbook.Worksheets("HR")
' Find the last rows in AT&T and HR sheets
lastRowAT&T = wsAT&T.Cells(wsAT&T.Rows.Count, "D").End(xlUp).Row
lastRowHR = wsHR.Cells(wsHR.Rows.Count, "AC").End(xlUp).Row
' Set the title in column E of AT&T sheet
wsAT&T.Cells(1, 5).Value = "Dept code"
' Loop through the AT&T sheet from row 2 onwards
For i = 2 To lastRowAT&T
deptCode = ""
' Loop through the HR sheet to find a match
For j = 2 To lastRowHR
If wsAT&T.Cells(i, 4).Value = wsHR.Cells(j, 29).Value Then ' Column AC is the 29th column
If wsHR.Cells(j, 13).Value = 0 Then ' Column M is the 13th column
deptCode = wsHR.Cells(j, 14).Value ' Column N is the 14th column
Else
deptCode = wsHR.Cells(j, 13).Value
End If
Exit For
End If
Next j
' Paste the deptCode into column E of the AT&T sheet
wsAT&T.Cells(i, 5).Value = deptCode
Next i
End Sub
This is the code of the problem I’m solving.
I was running this and it says object error
New contributor
Jack bass is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1