0% found this document useful (0 votes)
58 views1 page

Question No. 21 VBA Code For Practice

Uploaded by

Rehan Sabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views1 page

Question No. 21 VBA Code For Practice

Uploaded by

Rehan Sabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Option Explicit

Sub DisplayEmployeesOver2Years()
Dim wsNew As Worksheet
Dim wsData As Worksheet
Dim lastRow As Long
Dim i As Long
Dim yearsOfWork As Long

' Set the data worksheet


Set wsData = ThisWorkbook.Worksheets("Sheet1") ' Replace "Sheet1" with the
actual name of your data worksheet

' Create a new worksheet for the employee list


Set wsNew = ThisWorkbook.Worksheets.Add
wsNew.Name = "Employees Over 2 Years"

' Copy headers to the new worksheet


wsData.Rows(1).Copy Destination:=wsNew.Rows(1)

' Find the last row in the data worksheet


lastRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row

' Loop through the data and copy employees with over 2 years of service to the
new worksheet
For i = 2 To lastRow
yearsOfWork = DateDiff("yyyy", wsData.Cells(i, 6).Value, Date)
If yearsOfWork >= 2 Then
wsData.Rows(i).Copy
Destination:=wsNew.Rows(wsNew.Cells(wsNew.Rows.Count, 1).End(xlUp).Row + 1)
End If
Next i

' Autofit columns in the new worksheet


wsNew.Columns.AutoFit

' Provide a message with the count of employees over 2 years


MsgBox "Employee list for those working over 2 years has been generated on the
'Employees Over 2 Years' worksheet."
End Sub

You might also like