I'm helping my manager working on a personnel planning file and which has 3 dimensions: employee, week, and project name.
I want to fill in the blank cells between the project start date and End Date (see highlighted). I wrote the below code but it replaces the second project name with the first. (e.g. project 1 / project 2 for employee 1, project 3/project 6 for employee 2), and copy it until the end of the last project.
How can I proof-read my code and improve it to complete the purpose it is designed for?
Sub FillProjectDate_TEST1()
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim i As Long, j As Long
Dim startDate As Date, endDate As Date
Dim project As String
Set ws = ThisWorkbook.Sheets("Timeline")
' Find the last row and last column with data
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row
lastCol = ws.Cells(3, ws.Columns.Count).End(xlToLeft).Column
' Loop through each row starting from row 4
For i = 4 To lastRow
' Reset start and end dates for each row
startDate = 0
endDate = 0
' Loop through each column (week). First week is in column B.
For j = 2 To lastCol
' Check if the cell has a project name
If ws.Cells(i, j).Value <> "" Then
' If start date is not set, set it
If startDate = 0 Then
startDate = ws.Cells(3, j).Value
project = ws.Cells(i, j).Value ' Store project name
End If
' Always update end date to the current date
endDate = ws.Cells(3, j).Value
End If
Next j
' Fill in cells between start and end dates with project name
If startDate <> 0 And endDate <> 0 Then
For j = 1 To lastCol
If ws.Cells(3, j).Value >= startDate And ws.Cells(3, j).Value <= endDate Then
ws.Cells(i, j).Value = project
End If
Next j
End If
Next i
End Sub
[UPDATE]
Thanks again @taller for modifying the code.
One more question from my side. I want to modify the code to fill blanks to the end project date. In the case where thereas an overlapping period, how can i realistically replace with the second project name? From a starting data of this: Project Start/End Date It should be converted to something like this: Final Result
Update
Update2:
Note: The code can only handle
two
overlapping projects.