Hello
I need fixing formatting problem in first row for each range.
the headers should just add in first row for each range , but will repeat !
based on code when reach 27th or bigger than 27 th and less 31th then will copy data from userform to FORM sheet.
I put the right way to the bottom how should be the headers.
the code will copy to the bottom for each current month alone based on condition for specific days.
Private Sub CommandButton1_Click()
Dim i As Long
Dim lastrow As Long
Dim sheet2 As Worksheet
Dim currentMonth As String
Dim copyDate As Date
Dim remainingDays As Long
Dim headersWritten As Boolean
Set sheet2 = ThisWorkbook.Sheets("FORM") ' Replace with the correct sheet name if necessary
lastrow = sheet2.Cells(sheet2.Rows.Count, 1).End(xlUp).Row
headersWritten = (sheet2.Cells(1, 1).Value = "MONTH" And sheet2.Cells(1, 2).Value = "ITEM" _
And sheet2.Cells(1, 3).Value = "NAME" And sheet2.Cells(1, 4).Value = "BALANCE")
If Not headersWritten Then
sheet2.Cells(1, 1).Value = "MONTH"
sheet2.Cells(1, 2).Value = "ITEM"
sheet2.Cells(1, 3).Value = "NAME"
sheet2.Cells(1, 4).Value = "BALANCE"
End If
currentMonth = Format(Date, "mmm-yy")
Dim alreadyCopied As Boolean
alreadyCopied = False
For i = 2 To lastrow
If sheet2.Cells(i, 1).Value = currentMonth Then
alreadyCopied = True
Exit For
End If
Next i
If alreadyCopied Then
MsgBox "The data has already been copied for this month!", vbExclamation
Exit Sub
End If
copyDate = Date
If Day(copyDate) < 27 Then
remainingDays = 27 - Day(copyDate)
MsgBox "Warning: You need to wait " & remainingDays & " more days to copy the data.", vbExclamation
Exit Sub
ElseIf Day(copyDate) >= 27 And Day(copyDate) <= 31 Then
With Me.ListBox1
For i = 0 To .ListCount - 1
sheet2.Cells(lastrow + 1, 1).Value = currentMonth
sheet2.Cells(lastrow + 1, 2).Value = .List(i, 0)
sheet2.Cells(lastrow + 1, 3).Value = .List(i, 1)
sheet2.Cells(lastrow + 1, 4).Value = .List(i, 2)
lastrow = lastrow + 1
Next i
End With
MsgBox "Data successfully copied for " & currentMonth, vbInformation
Else
MsgBox "Warning: You can only copy data between the 27th and 31st of the month.", vbExclamation
Exit Sub
End If
End Sub