By: Shamima Sultana

In reply to Asger.

Hello Asger

You are most welcome. However, different formats might show due to mixed regional settings or VBA interpreting some dates incorrectly. To enforce consistency, we can modify the code to always use a single format, regardless of system settings.

Here’s an updated version that ensures the date format is consistently dd/mm/yyyy:

Sub Create_Calendar()

Dim formatString As String
formatString = "dd/mm/yyyy" ' Set a consistent date format

For i = 1 To 42
If i < Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)) Then
Controls("C" & i).Caption = Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), "d")

Controls("C" & i).ControlTipText = Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), formatString)

ElseIf i >= Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)) Then
Controls("C" & i).Caption = Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), "d")

Controls("C" & i).ControlTipText = Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), formatString)
End If

' Highlight current month and set focus on today’s date
If Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), "mmmm") = Month_Box.Value Then

Controls("C" & i).BackColor = &HFFFFFF
Controls("C" & i).Font.Bold = True

If Format(DateAdd("d", i - Weekday(CDate(Month_Box.Value & "/1/" & Year_Box.Value)), _
CDate(Month_Box.Value & "/1/" & Year_Box.Value)), formatString) = Format(Date, formatString) Then
Controls("C" & i).SetFocus
End If

Else
Controls("C" & i).BackColor = &H8000000F
Controls("C" & i).Font.Bold = False
End If
Next i

End Sub

To ensure the calendar automatically hides after a date is selected, you can modify the code to make the calendar invisible after a date is picked. Add the following code to the Calendar1_Click event, which will trigger each time a date is chosen:

Private Sub Calendar1_Click()
DateTextBox.Value = Format(Calendar1.Value, "dd/mm/yyyy") ' Use consistent date format
Calendar1.Visible = False ' Hide the calendar automatically after selection
End Sub

If you’re using buttons for each day as clickable dates, include the Calendar1.Visible = False line in the click event for each button:

Private Sub C1_Click()
DateTextBox.Value = Format(DateAdd("d", 0, Calendar1.Value), "dd/mm/yyyy") ' Adjust format here
Calendar1.Visible = False
End Sub

This approach ensures the calendar closes automatically after a date selection. Let me know if this solves it!

Regards
ExcelDemy