Vba for calendar in excel

Date Picker Calendar in Excel VBA

Oftentimes, users want to click a button and select a date. This is no different for Excel developers. Check out this ActiveX control by Microsoft that allows users to do just that. It’s a little old school looking, but actually has quite a nice feel to it.

Start by creating a userform and enabling the control by Right-clicking on the Tools menu and click Add additional tools

Now, let’s add this to the userform!

Calendar In Excel using Microsoft MonthView Control

In the downloadable workbook, you’ll see the control was renamed to ‘fCal’. When you double-click the control you’ll see the following code which is the DateClick event of that control:

code snippet

This userform cleverly has two labels to store relevant info on the Userform that summoned it. 1.) The name of the userform that called it and 2.) The name of the control or textbox that needs the date sent to it.

Then, this code above loops through all userforms in your project until it finds one that matches the label for the Userform (lblUF) and the label for the textbox needed (lblCtrlName).

Also, you may need to enable Microsoft Windows Common Controls -2 6.0 (SP6) by using Tools->References and clicking:

s

Stop Wasting Your Time

Experience Ultimate Excel Automation & Learn to “Make Excel Do Your Work For You”

s

Watch Us Make a Calendar In Excel On YouTube:

This website uses cookies to improve your experience. We’ll assume you’re ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Wait A Second!

Thank you for visiting! Here’s a FREE gift for you!

Enroll In My FREE VBA Crash Course For FREE!

Learn how to write macros from scratch, make buttons and simple procedures to automate tasks.

Ah, The complexities of automation! The versatile and multifaceted world of Excel VBA offers an array of tools and functionalities to streamline tasks and make life easier. Yet, despite its vast offerings, not all versions of Excel VBA come equipped with the desired calendar control, one that would allow for the selection of dates in a visually appealing manner, instead of the tedious manual input of dates into cells or text boxes. But fear not! For we shall embark on a journey, one that will unravel the mysteries of crafting a customized, dynamic calendar in Excel VBA using VBA User Forms and Command Buttons.

Step 1: Baffling Beginnings

Our journey begins with the creation of a User Form, a task achieved by navigating to the VBA editor and right-clicking on the ‘Project’ option in the Project Explorer, selecting ‘Insert’, followed by ‘User Form’. Voila! A new User Form will mysteriously appear, waiting to be customized to your whims and fancies.

Step 2: Commanding Conundrum

Next, we add a series of Command Buttons to the User Form, buttons that will act as our navigational tools, leading us through the calendar and enabling us to switch between months and years. And, to further confuse the matter, we add combo boxes, providing the option for the user to choose the month and year.

Step 3: Cryptic Code

With the controls in place, it’s time to delve into the code, to bring our dynamic calendar to life. To start, we write a function to generate the calendar based on the selected month and year, populating it with the correct number of days and illuminating the current date. And, as a bonus, we add a feature to highlight already existing dates in the text box or label by comparing the dates and marking them with a small star symbol, making the calendar even more user-friendly.

Watch the step-by-step video tutorials to learn the design and coding

Step 4: Calling the Calendar

Finally, with the dynamic calendar fully functional, we can summon it in our VBA project by using the ‘SelectedDate’ function. There are two methods to call this function:

Method 1: Call Calendar.SelectedDate(Me.TextBox1)

Method 2: Me.TextBox1.Value = Calendar.SelectedDate

The first method calls the calendar control and passes the value of the text box to the ‘SelectedDate’ function, while the second method calls the calendar control and assigns the selected date to the text box.

Move the Calendar control in from One to another VBA Project:

Just move this calendar form in your VBA project just drag it using mouse

Move Calendar to your VBA Project using Mouse

Move Calendar to your VBA Project using Mouse

Bursting with Conclusions

And there you have it, a perplexing puzzle solved, a dynamic calendar crafted with the use of Excel VBA User Forms and Command Buttons. The calendar control, now at your beck and call, can be used in various VBA projects, and is easily summoned using the ‘SelectedDate’ function. And, with a few modifications, additional functionality, such as highlighting of existing dates or changes in style and appearance, can be added to further confuse and bewilder.

This Fully Functional Dynamic Calendar Control in VBA, we have designed to use in VBA project. You can use it for Excel Cells, Textbox, Label and Command Button etc. It is extremely easy to call this Calendar for your VBA Project. You can call this with two methods.

Click here to download this Fully Function Calendar Control

Author: Oscar Cronquist Article last updated on October 03, 2019

This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The calendar sheet allows you to enter a year and use a drop down list to select a month.

A small VBA event code tracks which cell you have selected and shows the corresponding events accordingly.

How this workbook works

The animated image above shows how to enter data and how to select a given date. Today’s date is highlighted yellow, days with one or more events are also highlighted, in this example blue.

Excel extracts data dynamically meaning the named range grows automatically when new data is entered, we don’t need to change the formula cell references.

How I created the calendar

Table of Contents

  1. Calendar
    1. Drop down lists
    2. Headers
    3. Calculating dates (formula)
  2. Conditional formatting
    1. Today
    2. Dates not in selected month
    3. Events
  3. Formulas
    1. Dynamic named range
    2. Calendar sheet
    3. How to create an array formula
  4. Visual basic for applications
  5. Get excel *.xlsm file

Drop down lists

Select year

  1. Select cell B2
  2. Go to tab «Data»
  3. Press with left mouse button on «Data Validation» button
  4. Allow: List
  5. Source:2012,2013,2014,2015,2016
  6. Press with left mouse button on OK

Select month

  1. Select cell E4
  2. Go to tab «Data»
  3. Press with left mouse button on «Data Validation» button
  4. Allow: List
  5. Source:January, February, March, April, May, June, July, August, September, October, November, December
  6. Press with left mouse button on OK

Headers

Type Year: in cell B2, Month: in cell E2 and so on…

Calculating dates (formula)

  1. Select cell B5
  2. Formula:

    =DATE($C$2,MATCH($E$2,{«January»; «February»; «March»; «April»; «May»; «June»; «July»; «August»; «September»; «October»; «November»; «December»},0),1)-WEEKDAY(DATE($C$2,MATCH($E$2,{«January»; «February»; «March»; «April»; «May»; «June»; «July»; «August»; «September»; «October»; «November»; «December»},0),1),2)+1

  3. Select cell B6
  4. Formula:

    =B5+1

  5. Copy cell B6 (Ctrl + c)
  6. Select cell range D5:H5
  7. Paste  (Ctrl + v)
  8. Select cell B6
  9. Formula:

    =B5+7

  10. Copy cell range C5:H5
  11. Select cell range C6:H6
  12. Paste (Ctrl + v)
  13. Copy cell range B6:H6 (Ctrl + c)
  14. Select cell range B7:H10
  15. Paste (Ctrl + v)

Conditional formatting

Highlight Today

  1.  Select cell range B5:H10
  2. Go to tab «Home»
  3. Press with left mouse button on «Conditional formatting» button
  4. Press with left mouse button on «New Rule…»
  5. Press with left mouse button on «Use a formula to determine which cells to format»
  6. Format values where this formula is true:
    =B5=TODAY()
  7. Press with left mouse button on «Format…» button
  8. Go to «Fill» tab
  9. Pick a color
  10. Press with left mouse button on OK
  11. Press with left mouse button on OK

Change font color for dates not in selected month

  1. Repeat 1-5 steps above
  2. =MONTH(B5)<>MONTH($B$6)
  3. Press with left mouse button on «Format…» button
  4. Go to «Font» tab
  5. Pick a color
  6. Press with left mouse button on OK
  7. Press with left mouse button on OK

Highlight days with events

  1. Repeat 1-5 steps above
  2. =OR(B5=INT(INDEX(Data,0,1)))
  3. Press with left mouse button on «Format…» button
  4. Go to «Fill» tab
  5. Pick a color
  6. Press with left mouse button on OK
  7. Press with left mouse button on OK

Formulas

Dynamic named range

  1. Select sheet «Data»
  2. Go to tab «Formulas»
  3. Press with left mouse button on «Name Manager» button
  4. Press with left mouse button on «New…»
  5. Name: Data
  6. Refers to:
    =OFFSET(Data!$A$2,,,COUNTA(Data!$A$1:$A$1000)-1,3)
  7. Press with left mouse button on OK!
  8. Press with left mouse button on Close

Event formulas

  1. Select sheet «Calendar»
  2. Select cell B13
  3. Array formula:

    =IFERROR(INT(INDEX(Data, SMALL(IF(INT(INDEX(Data, 0, 1))=$G$2, MATCH(ROW(Data), ROW(Data)), «»), ROW(A1)), COLUMN(A1))), «»)

  4. Enter this formula as an array formula, see these steps if you don’t know how.
  5. Select cell D13
  6. Array formula:

    =IFERROR(INDEX(Data, SMALL(IF(INT(INDEX(Data, 0, 1))=$G$2, MATCH(ROW(Data), ROW(Data)), «»), ROW(B1)), COLUMN(A1)), «»)

  7. Select cell F13
  8. Array formula:

    =IFERROR(INDEX(Data, SMALL(IF(INT(INDEX(Data, 0, 1))=$G$2, MATCH(ROW(Data), ROW(Data)), «»), ROW(C1)), COLUMN(B1)), «»)

  9. Select cell H13
  10. Array formula:

    =IFERROR(INDEX(Data, SMALL(IF(INT(INDEX(Data, 0, 1))=$G$2, MATCH(ROW(Data), ROW(Data)), «»), ROW(D1)), COLUMN(C1)), «»)

How to create an array formula

  1. Select a cell
  2. Press with left mouse button on in formula bar
  3. Paste array formula
  4. Press and hold Ctrl + Shift
  5. Press Enter

Visual basic for applications

  1. Press with right mouse button on on Calendar sheet
  2. Press with left mouse button on «View code»
  3. Copy vba code below.
    'Event code that is rund every time a cell is selected in worksheet Calendar
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    
    'Check if selected cell address is in cell range B5:H10
    If Not Intersect(Target, Range("B5:H10")) Is Nothing Then
    
    'Save date to cell G2
    Range("G2") = Target.Value
    End If
    
    End Sub
    
  4. Paste to worksheet module.

Note, save your workbook with file extension *.xlsm in order to attach the code to the workbook.

Hide value in cell G2

  1. Select cell G2
  2. Press Ctrl + 1
  3. Go to tab «Number»
  4. Select category: Custom
  5. Type ;;;
  6. Press with left mouse button on OK!

Calendar-event-finish

Calendar category

test

Calendar – monthly view
This article describes how to build a calendar showing all days in a chosen month with corresponding scheduled events. What’s […]

test

Plot date ranges in a calendar part 2
I will in this article demonstrate a calendar that automatically highlights dates based on date ranges, the calendar populates names […]

test

test

Plot date ranges in a calendar
The image above demonstrates cells highlighted using a conditional formatting formula based on a table containing date ranges. The calendar […]

test

Heat map yearly calendar
The calendar shown in the image above highlights events based on frequency. It is made only with a few conditional […]

test

Highlight events in a yearly calendar
This article demonstrates how to highlight given date ranges in a yearly calendar, this calendar allows you to change the […]

test

Monthly calendar template
The image above shows a calendar that is dynamic meaning you choose year and month and the calendar instantly updates […]

test

Create a drop down calendar
The drop down calendar in the image above uses a «calculation» sheet and a named range. You can copy the drop-down […]

test

test

Pivot Table calendar
This article demonstrates how to build a calendar in Excel. The calendar is created as a Pivot Table which makes […]

test

Calendar with scheduling [vba]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]

test

Yet another Excel Calendar
What’s on this page How to use this Excel Calendar How to add events How I built this calendar Worksheet […]

test

test

Monthly calendar template #2
I have created another monthly calendar template for you to get. Select a month and year in cells A1 and […]

test

Weekly appointment calendar
This weekly calendar is easy to customize, you can change calendar settings in sheet «Settings»: Start date (preferably a Sunday or […]

If then else statement category

Macro category

test

Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]

test

Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]

test

test

Working with COMBO BOXES [Form Controls]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]

test

Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]

test

test

test

Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]

test

Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]

test

test

test

Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]

test

test

test

test

test

test

test

Functions in this article

More than 1300 Excel formulas

Excel formula categories

Excel categories

Latest updated articles.

More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.

More than 1300 formulas organized in subcategories.

Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.

Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.

Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.

Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.

Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.

The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.

An Excel feature that lets you visualize data in a graph.

Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.

Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.

VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.

A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.

UDF stands for User Defined Functions and is custom built functions anyone can create.

A list of all published articles.

A calendar in Microsoft Excel comes in handy if you’ve a busy schedule. Although an Excel calendar is an outstanding tool that can assist you to stay prepared when it comes to vital events, appointments, activities, meetings, etc. Therefore, today we are here to discuss how to create calendar in Excel or how to insert calendar in Excel effortlessly.

So, without any further ado, let’s get started…

To repair corrupt Excel file, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

If you want to keep your data in a more organized way then a proper calendar system is very important for the right time management. Luckily Excel offers different ways to create calendars. Let’s know about each of them one by one in detail.

Method 1: Insert Calendar In Excel Using Date Picker Control

Well putting the drop-down calendar in Excel is quite easy to do but just because the time and date picker control are hidden so many users don’t know where it actually exists.

Here is the complete method to create a calendar in Excel perform this task step by step:

Note: Date Picker control of Microsoft works Microsoft’s very smoothly in the Excel 32-bit versions but not in Excel 64-bit version.

  1. Enable The Developer Tab on Excel ribbon.

Excel date picker control actually belongs to the ActiveX controls family, which comes under the Developer tab. Though this Excel Developer tab is kept hidden you can enable its visibility.

  • On the Excel ribbon, you have to make a right-click, and after that choose the option Customize the Ribbon…. This will open the Excel options.
  • From the opened window go to the right-hand side section. Now from customizing the ribbon section, you have to select the Main Tabs. In the appearing main tab list check the Developer box option and then click the OK button.

Date Picker control 1

Also Read: How to Create a Flowchart in Excel? (Step-By-Step Guide)

  1. Insert The Calendar Control

Well, the Excel drop-down calendar is technically known as Microsoft Date and Time Picker Control.

To apply this in the Excel sheet, perform the following steps:

  • Hit the Developer tab and then from the Controls group, you have to make a tap over arrow sign present within the Insert tab.

Now from the ActiveX Controls choose the “More Controls” button.

Date Picker control 2

  • From the opened dialog box of More Controlsselect the Microsoft Date and Time Picker Control 6.0 (SP6). After that click to the OK

Date Picker control 3

  • Hit the cell, in which you have to enter the calendar control.

You will see that a drop-down calendar control starts appearing on your Excel sheet:

Date Picker control 4

Once this date picker control is been inserted, you will see that the EMBED formula starts appearing within the formula bar.

This gives detail to your Excel application about what kind of control is embedded within the sheet. You can’t change edit or delete this control because this will show the error “Reference is not valid“.

Adding the ActiveX control such date picker automatically enables the design mode which will allow you to change the properties and appearance of any freshly added control. The most obvious modification that you need to make at this time is resizing the calendar control and then linking it back to any specific cell.

For activating the Excel drop-down calendar option, hit the Design tab, and then from the Controls group, disable the Design Mode:

Date Picker control 5

  • Now, make a tap over the drop-down arrow for showing up the calendar and then select the date as per your need.
  • Click the dropdown arrow to show the calendar in Excel and choose your desired date.

Date Picker control 6

Note:

If MS date picker control is now not available within the list of More Controls. This situation mainly arises due to the following reasons.

  • While you are running the MS Office 64 bit version. As there is no official date picker control available in the Office 64-bit.
  • Calendar control i.e mscomct2.ocx is now not present or it is not registered on your PC.
  1. Customize Calendar Control

After the addition of the calendar control on your Excel sheet, now you have to shift this calendar control on the desired location and then resize it to get an easy fit within a cell.

  • For resizing this date picker control, you have to enable the Design Mode after that drag this control from the corner section:

Date Picker control 7

Or else you after enabling the Design Mode on, from the calendar control group choose the Properties tab:

Date Picker control 8

  • From the opened Properties window, you have to set the desired width, height, font size and style:

Create Calendar In Excel

  • To shift the Excel date picker control, place your mouse pointer over that and when the cursor changes into a four-pointed arrow sign, just drag the object wherever you want to place it.

Date Picker control 10

  1. Link Excel Calendar Control With The Cell

After successfully adding the calendar drop-down in excel, you need to link it with some specific cell. This step very compulsory to perform if you want to make use of any selected dates with the formulas.

Suppose you are writing the formula for counting up the order’s number between any specific dates. For stopping any other from entering wrong dates such as 2/30/2016 you have inserted a drop-down calendar within 2 cells.

The COUNTIF formula that you have applied for calculating a number of orders will return the value “0” even if the orders are present.

Date Picker control 11

Well, the main reason can be that your Excel is unable to recognize the value present in the date picker control. This problem will persist until you link the control with some specific cell. Here is the step that you need to perform:

  1. Selecting the calendar control you have to enable the Design Mode.
  2. Go to the Developer tab and then from the control group tap to the
  3. In the opened Properties” windows, assign cell reference in the LinkedCell property (here I have written A3):

Create Calendar In Excel

If Excel shows the following error Can’t set cell value to NULL…” then click the OK button to ignore this.

After selecting the date from the drop-down calendar, the date will immediately start appearing in the linked cell. Now excel won’t face any issue in understanding the dates and the formula referencing done in the linked cells will work smoothly.

Create Calendar In Excel

If you don’t need to have extra dates then link the date picker control with the cells where they are present.

Also Read: 4 Ways To Create Drop-Down List In Excel

Method 2: Using Excel Calendar Template

In Excel, there are handy graphic options with the clipart, tables, drawing tools, charts, etc. Using these options one can easily create a monthly calender or weekly calendar with special occasion dates or photos.

So go with the Excel calendar template which is the fastest and easiest way to create calendar in Excel using worksheet data.

Here are the steps to create calendar from Excel spreadsheet data using the template.

  • Click the FileNew after that in the search box you have to type “calendar”.
  • Excel will make search thousands of online templates and then shows you the selected calendar templates which are grouped into the following categories.

Create Calendar In Excel

  • Choose the calendar template as per your requirement, and then tap to the Create.

excel calender template 2

That’s all you need to do…!

Excel calendar template will be opened from the new Excel workbook and then print or customize as per your need.  Usually, Excel weekly calendar templates are set with a year, whereas in some templates you can set a day for starting a week.

Note: for displaying always the current year in your excel calendar just assign a simple formula like this in the cell of the year: =YEAR(TODAY())

Create Calendar In Excel

In this way, you can easily insert the drop-down calendar. Also, you can make a printable Excel calendar.

Method 3: Create Calendar In Excel Using VBA Code

In this method, you will get know-how using the Visual Basic for Applications(VBA) macro code you can create calendar in Excel.

  1. Open your Excel workbook.
  2. For excel 2003 users: Go to the Tools menu, and then hit the Macro tab. After that choose the Visual Basic Editor.

For Excel 2007 or later users: go to the Developer tab from the Excel ribbon and choose Visual Basic.

  1. From the Insert menu, choose the Module option.
  2. Now paste the VBA code which is given below into the opened sheet of the module.
  3. Go to the File menu and choose the Close and Return to Microsoft Excel.
  4. Now make a selection of the Sheet1
  5. From the Tools menu, go to the Macro tab. After that choose the Macros icon.
  6. Now you have to choose the CalendarMaker Now press the Run button to create Excel calendar.

Visual Basic Procedure To Create a Calendar In Excel:

You have to paste this code in the module sheet.

Sub CalendarMaker()

‘ Unprotect sheet if had previous calendar to prevent error.
ActiveSheet.Protect DrawingObjects:=False, Contents:=False, _
Scenarios:=False
‘ Prevent screen flashing while drawing calendar.
Application.ScreenUpdating = False
‘ Set up error trapping.
On Error GoTo MyErrorTrap
‘ Clear area a1:g14 including any previous calendar.
Range(“a1:g14”).Clear
‘ Use InputBox to get desired month and year and set variable
‘ MyInput.
MyInput = InputBox(“Type in Month and year for Calendar “)
‘ Allow user to end macro with Cancel in InputBox.
If MyInput = “” Then Exit Sub
‘ Get the date value of the beginning of inputted month.
StartDay = DateValue(MyInput)
‘ Check if valid date but not the first of the month
‘ — if so, reset StartDay to first day of month.
If Day(StartDay) <> 1 Then
StartDay = DateValue(Month(StartDay) & “/1/” & _
Year(StartDay))
End If
‘ Prepare cell for Month and Year as fully spelled out.
Range(“a1”).NumberFormat = “mmmm yyyy”
‘ Center the Month and Year label across a1:g1 with appropriate
‘ size, height and bolding.
With Range(“a1:g1”)
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
.Font.Size = 18
.Font.Bold = True
.RowHeight = 35
End With
‘ Prepare a2:g2 for day of week labels with centering, size,
‘ height and bolding.
With Range(“a2:g2”)
.ColumnWidth = 11
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.Orientation = xlHorizontal
.Font.Size = 12
.Font.Bold = True
.RowHeight = 20
End With
‘ Put days of week in a2:g2.
Range(“a2”) = “Sunday”
Range(“b2”) = “Monday”
Range(“c2”) = “Tuesday”
Range(“d2”) = “Wednesday”
Range(“e2”) = “Thursday”
Range(“f2”) = “Friday”
Range(“g2”) = “Saturday”
‘ Prepare a3:g7 for dates with left/top alignment, size, height
‘ and bolding.
With Range(“a3:g8”)
.HorizontalAlignment = xlRight
.VerticalAlignment = xlTop
.Font.Size = 18
.Font.Bold = True
.RowHeight = 21
End With
‘ Put inputted month and year fully spelling out into “a1”.
Range(“a1”).Value = Application.Text(MyInput, “mmmm yyyy”)
‘ Set variable and get which day of the week the month starts.
DayofWeek = WeekDay(StartDay)
‘ Set variables to identify the year and month as separate
‘ variables.
CurYear = Year(StartDay)
CurMonth = Month(StartDay)
‘ Set variable and calculate the first day of the next month.
FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
‘ Place a “1” in cell position of the first day of the chosen
‘ month based on DayofWeek.
Select Case DayofWeek
Case 1
Range(“a3”).Value = 1
Case 2
Range(“b3”).Value = 1
Case 3
Range(“c3”).Value = 1
Case 4
Range(“d3”).Value = 1
Case 5
Range(“e3”).Value = 1
Case 6
Range(“f3”).Value = 1
Case 7
Range(“g3”).Value = 1
End Select
‘ Loop through range a3:g8 incrementing each cell after the “1”
‘ cell.
For Each cell In Range(“a3:g8”)
RowCell = cell.Row
ColCell = cell.Column
‘ Do if “1” is in first column.
If cell.Column = 1 And cell.Row = 3 Then
‘ Do if current cell is not in 1st column.
ElseIf cell.Column <> 1 Then
If cell.Offset(0, -1).Value >= 1 Then
cell.Value = cell.Offset(0, -1).Value + 1
‘ Stop when the last day of the month has been
‘ entered.
If cell.Value > (FinalDay – StartDay) Then
cell.Value = “”
‘ Exit loop when calendar has correct number of
‘ days shown.
Exit For
End If
End If
‘ Do only if current cell is not in Row 3 and is in Column 1.
ElseIf cell.Row > 3 And cell.Column = 1 Then
cell.Value = cell.Offset(-1, 6).Value + 1
‘ Stop when the last day of the month has been entered.
If cell.Value > (FinalDay – StartDay) Then
cell.Value = “”
‘ Exit loop when calendar has correct number of days
‘ shown.
Exit For
End If
End If
Next

‘ Create Entry cells, format them centered, wrap text, and border
‘ around days.
For x = 0 To 5
Range(“A4”).Offset(x * 2, 0).EntireRow.Insert
With Range(“A4:G4”).Offset(x * 2, 0)
.RowHeight = 65
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlTop
.WrapText = True
.Font.Size = 10
.Font.Bold = False
‘ Unlock these cells to be able to enter text later after
‘ sheet is protected.
.Locked = False
End With
‘ Put border around the block of dates.
With Range(“A3”).Offset(x * 2, 0).Resize(2, _
7).Borders(xlLeft)
.Weight = xlThick
.ColorIndex = xlAutomatic
End With

With Range(“A3”).Offset(x * 2, 0).Resize(2, _
7).Borders(xlRight)
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Range(“A3”).Offset(x * 2, 0).Resize(2, 7).BorderAround _
Weight:=xlThick, ColorIndex:=xlAutomatic
Next
If Range(“A13”).Value = “” Then Range(“A13”).Offset(0, 0) _
.Resize(2, 8).EntireRow.Delete
‘ Turn off gridlines.
ActiveWindow.DisplayGridlines = False
‘ Protect sheet to prevent overwriting the dates.
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True

‘ Resize window to show all of calendar (may have to be adjusted
‘ for video configuration).
ActiveWindow.WindowState = xlMaximized
ActiveWindow.ScrollRow = 1

‘ Allow screen to redraw with calendar showing.
Application.ScreenUpdating = True
‘ Prevent going to error trap unless error found by exiting Sub
‘ here.
Exit Sub
‘ Error causes msgbox to indicate the problem, provides new input box,
‘ and resumes at the line that caused the error.
MyErrorTrap:
MsgBox “You may not have entered your Month and Year correctly.” _
& Chr(13) & “Spell the Month correctly” _
& ” (or use 3 letter abbreviation)” _
& Chr(13) & “and 4 digits for the Year”
MyInput = InputBox(“Type in Month and year for Calendar”)
If MyInput = “” Then Exit Sub
Resume
End Sub

Note: You can customize the above code as per your requirement.

How Do I Make Excel Calendar Update Automatically?

Automatization is the chief strength of Microsoft Excel. However, if you need to create your calendar update automatically then use the formula mentioned below:

“= EOMONTH (TODAY() , – 1) +1”.

Well, the above formula employs “TODAY” feature to locate the present date & calculates the 1st day of the month with the “EOMONTH” feature.

Related FAQs:

Does Excel Have a Calendar Template?

Yes, of course, Microsoft Excel have a wide variety of calendar templates that can be used easily.

What Is the Formula to Create a Calendar in Excel?

=DATE(A2,A1,1) is the formula that can be used to create a calendar in MS Excel. All you need to do is to select the blank cell for showing the starting month’s date, then simply enter =DATE(A2,A1,1) in a formula bar >> press Enter key.

Can You Insert a Calendar into An Excel Cell?

YES, you can insert a calendar into an Excel cell. For this, you have to go to File menu >> select Close & Return to MS Excel. After this, select a tab ‘Sheet1’. On Tools menu, simply point to the Macro, & select Macros. choose CalendarMaker >> select the Run to create a calendar.

Also Read: How To Create Backup Of Active Workbooks In Excel?

Wrap Up:

MS Excel offers its user a broad range of tools which will increase their productivity by using the projects, dates, and tracking events. In order to view the data of your Excel worksheet in calendar format, Microsoft will change your data and then import it into the Outlook. This will automatically change it into a calendar format.

Hopefully, you must have found an ample amount of information in this post. Thanks for reading this post….!

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

The sample file (added at the end of the post) has a Userform, Module and a Class Module. To incorporate this into your project, simply export the Userform, Module and the Class Module from the sample file and import it into your project.

Class Module Code

In the Class Module (Let’s call it CalendarClass) paste this code

Public WithEvents CommandButtonEvents As MSForms.CommandButton

'~~> Unload the form when the user presses Escape
Private Sub CommandButtonEvents_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If Not f Is Nothing Then If KeyAscii = 27 Then Unload f
End Sub

'~~> This section delas with showing/displaying controls
'~~> and updating different labels
Private Sub CommandButtonEvents_Click()
    f.Label6.Caption = CommandButtonEvents.Tag

    If Left(CommandButtonEvents.Name, 1) = "Y" Then
        If Len(Trim(CommandButtonEvents.Caption)) <> 0 Then
            CurYear = Val(CommandButtonEvents.Caption)                
            With f
                .HideAllControls
                .ShowMonthControls

                .Label4.Caption = CurYear
                .Label5.Caption = 2

                .CommandButton1.Visible = False
                .CommandButton2.Visible = False
            End With
        End If
    ElseIf Left(CommandButtonEvents.Name, 1) = "M" Then
        Select Case UCase(CommandButtonEvents.Caption)
            Case "JAN": CurMonth = 1
            Case "FEB": CurMonth = 2
            Case "MAR": CurMonth = 3
            Case "APR": CurMonth = 4
            Case "MAY": CurMonth = 5
            Case "JUN": CurMonth = 6
            Case "JUL": CurMonth = 7
            Case "AUG": CurMonth = 8
            Case "SEP": CurMonth = 9
            Case "OCT": CurMonth = 10
            Case "NOV": CurMonth = 11
            Case "DEC": CurMonth = 12
        End Select

        f.HideAllControls
        f.ShowSpecificMonth
    End If
End Sub

Module Code

In the Module (Let’s call it CalendarModule) paste this code

Option Explicit

Public Const GWL_STYLE = -16
Public Const WS_CAPTION = &HC00000

#If VBA7 Then
    #If Win64 Then
        Public Declare PtrSafe Function GetWindowLongPtr Lib "user32" Alias _
        "GetWindowLongPtrA" (ByVal hwnd As LongPtr, ByVal nIndex As Long) As LongPtr

        Public Declare PtrSafe Function SetWindowLongPtr Lib "user32" Alias _
        "SetWindowLongPtrA" (ByVal hwnd As LongPtr, ByVal nIndex As Long, _
        ByVal dwNewLong As LongPtr) As LongPtr
    #Else
        Public Declare PtrSafe Function GetWindowLongPtr Lib "user32" Alias _
        "GetWindowLongA" (ByVal hwnd As LongPtr, ByVal nIndex As Long) As LongPtr

        Private Declare Function SetWindowLongPtr Lib "user32" Alias _
        "SetWindowLongA" (ByVal hwnd As LongPtr, ByVal nIndex As Long, _
        ByVal dwNewLong As LongPtr) As LongPtr
    #End If

    Public Declare PtrSafe Function DrawMenuBar Lib "user32" _
    (ByVal hwnd As LongPtr) As LongPtr

    Private Declare PtrSafe Function FindWindow Lib "user32" Alias _
    "FindWindowA" (ByVal lpClassName As String, _
    ByVal lpWindowName As String) As LongPtr

    Private Declare PtrSafe Function SetTimer Lib "user32" _
    (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr, _
    ByVal uElapse As LongPtr, ByVal lpTimerFunc As LongPtr) As LongPtr

    Public Declare PtrSafe Function KillTimer Lib "user32" _
    (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr) As LongPtr

    Public TimerID As LongPtr

    Dim lngWindow As LongPtr, lFrmHdl As LongPtr
#Else

    Public Declare Function GetWindowLong _
    Lib "user32" Alias "GetWindowLongA" ( _
    ByVal hwnd As Long, ByVal nIndex As Long) As Long

    Public Declare Function SetWindowLong _
    Lib "user32" Alias "SetWindowLongA" ( _
    ByVal hwnd As Long, ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long

    Public Declare Function DrawMenuBar _
    Lib "user32" (ByVal hwnd As Long) As Long

    Public Declare Function FindWindowA _
    Lib "user32" (ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long

    Public Declare Function SetTimer Lib "user32" ( _
    ByVal hwnd As Long, ByVal nIDEvent As Long, _
    ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

    Public Declare Function KillTimer Lib "user32" ( _
    ByVal hwnd As Long, ByVal nIDEvent As Long) As Long

    Public TimerID As Long
    Dim lngWindow As Long, lFrmHdl As Long
#End If

Public TimerSeconds As Single, tim As Boolean
Public CurMonth As Integer, CurYear As Integer
Public frmYr As Integer, ToYr As Integer

Public f As frmCalendar

Enum CalendarThemes
    Venom = 0
    MartianRed = 1
    ArcticBlue = 2
    Greyscale = 3
End Enum

Sub Launch()
    Set f = frmCalendar

    With f
        .Caltheme = Greyscale
        .LongDateFormat = "dddd dd. mmmm yyyy" '"dddd mmmm dd, yyyy" etc
        .ShortDateFormat = "dd/mm/yyyy"  '"mm/dd/yyyy" or "d/m/y" etc
        .Show
    End With
End Sub

'~~> Hide the title bar of the userform
Sub HideTitleBar(frm As Object)
    #If VBA7 Then
        Dim lngWindow As LongPtr, lFrmHdl As LongPtr
        lFrmHdl = FindWindow(vbNullString, frm.Caption)
        lngWindow = GetWindowLongPtr(lFrmHdl, GWL_STYLE)
        lngWindow = lngWindow And (Not WS_CAPTION)
        Call SetWindowLongPtr(lFrmHdl, GWL_STYLE, lngWindow)
        Call DrawMenuBar(lFrmHdl)
    #Else
        Dim lngWindow As Long, lFrmHdl As Long
        lFrmHdl = FindWindow(vbNullString, frm.Caption)
        lngWindow = GetWindowLong(lFrmHdl, GWL_STYLE)
        lngWindow = lngWindow And (Not WS_CAPTION)
        Call SetWindowLong(lFrmHdl, GWL_STYLE, lngWindow)
        Call DrawMenuBar(lFrmHdl)
    #End If
End Sub

'~~> Start Timer
Sub StartTimer()
    '~~ Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

'~~> End Timer
Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub

'~~> Update Time
#If VBA7 And Win64 Then ' 64 bit Excel under 64-bit windows  ' Use LongLong and LongPtr
    Public Sub TimerProc(ByVal hwnd As LongPtr, ByVal uMsg As LongLong, _
    ByVal nIDEvent As LongPtr, ByVal dwTimer As LongLong)
        frmCalendar.Label1.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(0)
        frmCalendar.Label2.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(1)
    End Sub
#ElseIf VBA7 Then ' 64 bit Excel in all environments
    Public Sub TimerProc(ByVal hwnd As LongPtr, ByVal uMsg As Long, _
    ByVal nIDEvent As LongPtr, ByVal dwTimer As Long)
        frmCalendar.Label1.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(0)
        frmCalendar.Label2.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(1)
    End Sub
#Else ' 32 bit Excel
    Public Sub TimerProc(ByVal hwnd As Long, ByVal uMsg As Long, _
    ByVal nIDEvent As Long, ByVal dwTimer As Long)
        frmCalendar.Label1.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(0)
        frmCalendar.Label2.Caption = Split(Format(Time, "h:mm:ss AM/PM"))(1)
    End Sub
#End If

'~~> Improvement suggested by T.M (https://stackoverflow.com/users/6460297/t-m)
'(1) Get weekday name
Function wday(ByVal wd&, ByVal lang As String) As String
    ' Purpose: get weekday in "DDD" format
    wday = Application.Text(DateSerial(6, 1, wd), cPattern(lang) & "ddd")    ' the first day in year 1906 starts with a Sunday
End Function

'~~> Improvement suggested by T.M (https://stackoverflow.com/users/6460297/t-m)
'(2) Get month name
Function mon(ByVal mo&, ByVal lang As String) As String
    ' Example call: mon(12, "1031") or mon(12, "de")
    mon = Application.Text(DateSerial(6, mo, 1), cPattern(lang) & "mmm")
End Function

'~~> Improvement suggested by T.M (https://stackoverflow.com/users/6460297/t-m)
'(3) International patterns
Function cPattern(ByVal ctry As String) As String
    ' Purpose: return country code pattern for above functions mon() and wday()
    ' Codes: see https://msdn.microsoft.com/en-us/library/dd318693(VS.85).aspx
    ctry = LCase(Trim(ctry))
    Select Case ctry
        Case "1033", "en-us": cPattern = "[$-409]" ' English (US)
        Case "1031", "de": cPattern = "[$-C07]" ' German
        Case "1034", "es": cPattern = "[$-C0A]" ' Spanish
        Case "1036", "fr": cPattern = "[$-80C]" ' French
        Case "1040", "it": cPattern = "[$-410]" ' Italian
        ' more ...
    End Select
End Function

Userform Code

The Userform (Let’s call it frmCalendar) code is too big to be posted here. Please refer to the sample file.

Screenshot

enter image description here

Themes

enter image description here

Highlights

  1. No need to register any dll/ocx.
  2. Easily distributable. It is FREE.
  3. No Administratior Rights required to use this.
  4. You can select a skin for the calendar widget. One can choose from 4 themes Venom, MartianRed, ArticBlue and GreyScale.
  5. Choose Language to see Month/Day name. Support for 4 languages.
  6. Specify Long and Short date formats

Sample File

Sample File

Acknowlegements @Pᴇʜ, @chrisneilsen and @T.M. for suggesting improvements.

What’s New:

Bugs reported by @RobinAipperspach and @Jose fixed

The article about the way to build an automatic calendar is one of the most viewed on this website. But it is also the one with the most comments about the VBA code.

The purpose of this article is to explain each line of code and the logic of the program.

Sub Hide_Day()
Dim Num_Col As Long
   'This instruction cleans the content of the cells in your calendar
   Range("B7:AF13").ClearContents
   For Num_Col = 30 To 32
   ' Test if the month of the cells (row 6) is the same of the month selected (cell A1 or cells(1,1))
     If Month(Cells(6, Num_Col)) >= Cells(1, 1) Then
        Columns(Num_Col).Hidden = True
     Else
        Columns(Num_Col).Hidden = False
     End If
   Next
End Sub

Line 1: Creation of the name of the subroutine

In any VBA program all the code is written inside subroutines (Sub). Each subroutine must have a unique name in the project.

This name will be used in the calendar project to link the code with the dropdown list.

Sub Hide_Day()

Line 2 : Declare the variable

To evaluate the day’s value in the different columns, we need a create variable in order to read each column index (1, 2, 3, ….)

The variable Num_Col is declared (Dim) as a Whole Number (As Long) because the column index is obviously without decimal

Dim Num_Col As Long

Line 3 : Beginning of the loop

Now, we are going to create a loop to extend the variable Num_Col from 30 till 32.

For Num_Col = 30 To 32 

The reason why we start at the value 30 it’s because for any month, the days 29, 30 et 31 will be always in columns 30, 31 and 32

What is the value of the dates in column 30, 31 and 32

Line4 : Test between the month calculated in the cells and the month selected

Here is the trick of the program 😉😎

How Excel calculates date?

As you know, all the months have 28 days. But February could have 29 days each 4 years and 4 months have 30 days (April, June, September, November).

Just like that, it seems complex to create a test for each case. But on the other hand, Excel calculates precisely a date even if the number of days to add extend to the end of the month.

For instance, if we add 30 days to the 1st February 2019, Excel will return the date of the 3rd March 2019.

=DATE(2019;2;1)+30 => 03/03/2019

Calculated dates when February is selected

How to code a cell in VBA

In VBA, to read the contents of a cell, you just have to write Cells(index row, index column). So for A1, you will write Cells(1, 1) and for the cell AD6 with day 29, the code is Cells(6, 30)

But you can also replace one of the arguments of Cells by a variable like this Cells(6, Num_Col)

Construction of the test

Back to the calendar, for the month of February 2019, columns 30, 31 and 32 will have dates of March (and not February) because of the rule explained in the previous formula.

So, we will write a test between the month (return by the VBA function Month) of columns 30, 31 et 32 and the value returned by the dropdown menu for the month.

Result returns by the dropdown menu

So, the test will check if the month in the cells AD6, AE6 and AF6 (or Cells(6, 30), Cells(6, 31) et Cells(6,32)) is greater or equal to A1 (the cell linked to the dropdown menu for the month). But we don’t need to test the 3 columns, the variable will do it for us 😀

      If Month(Cells(6, Num_Col)) &gt;= Cells(1, 1) Then

Line 5 : Hide the column

If the test is True, the column Num_Col is hidden (Hidden = True).

     Columns(Num_Col).Hidden = True

Line 6 and 7 : Unhide the column

Otherwise (Else), which means the test is False, then the column Num_Col is un-hidden (Hidden = False)

      Else
         Columns(Num_Col).Hidden = False

This test looks stupid but in the case, your selected month has 31 days, you want to be able to display the previous column hidden (sooo clever 😉)

Line 8 and 9 : Close the instructions

In VBA, when you create a test or a loop, you must indicate when the test or the loop is ended.

At the end of the test If is End If, and the loop For, you must write the instruction Next

     End If
   Next  

Line 10 : Clear the data

After the loop on the 3 columns, the program will clear the contents of the range B6 to AF13 Range("B6:AF13") with the instruction ClearContents

   Range("B6:AF13").ClearContents  

Line 11 : End of the subroutine

Exactly like to indicate the end of a test or a loop, you must indicate that your subroutine is ended with the instruction End Sub

End Sub

Содержание

  1. VBA Excel. Элемент управления DTPicker
  2. Элемент управления DTPicker
  3. Добавление DTPicker на Toolbox
  4. Свойства поля с календарем
  5. Примеры кода VBA Excel с DTPicker
  6. Программное создание DTPicker
  7. Применение свойства CustomFormat
  8. Создание границ интервала дат
  9. How to add Calendar, Date-Picker?
  10. 5 Answers 5
  11. Fully Functional Dynamic Calendar Control in VBA
  12. Step 1: Baffling Beginnings
  13. Step 2: Commanding Conundrum
  14. Step 3: Cryptic Code
  15. Watch the step-by-step video tutorials to learn the design and coding
  16. Step 4: Calling the Calendar
  17. Move the Calendar control in from One to another VBA Project:
  18. Bursting with Conclusions

VBA Excel. Элемент управления DTPicker

Элемент управления пользовательской формы DTPicker (поле с календарем), предназначенный для выбора и ввода даты. Примеры кода VBA Excel с DTPicker.

Элемент управления DTPicker

При вызове календаря пользовательская форма теряет фокус – это видно на изображении. При редактировании даты непосредственно в текстовом поле DTPicker, формат поля позволяет изменять элементы даты (день, месяц, год) по отдельности.

Чтобы перемещаться между элементами даты, необходимо, или выбирать элемент мышью, или нажимать любой знак разделителя («.», «,» или «/») на клавиатуре. А клик по знаку «+» или «-», соответственно, увеличит или уменьшит значение элемента даты на единицу.

Если в элемент «год» ввести однозначное число или двузначное число, не превышающее двузначный остаток текущего года, через пару секунд автоматически добавятся первые две цифры текущего столетия (20). Если вводимое двузначное число превысит двузначный остаток текущего года, автоматически добавятся первые две цифры прошлого столетия (19).

DTPicker – это сокращение от слова DateTimePicker, не являющегося в VBA Excel ключевым словом, как и DatePicker.

Изначально на панели инструментов Toolbox нет ссылки на элемент управления DTPicker, поэтому ее нужно добавить самостоятельно.

Чтобы добавить DTPicker на панель инструментов Toolbox, кликните по ней правой кнопкой мыши и выберите из контекстного меню ссылку «Additional Controls…»:

В открывшемся окне «Additional Controls» из списка дополнительных элементов управления выберите строку «Microsoft Date and Time Picker Control»:

Нажмите кнопку «OK» и значок элемента управления DTPicker появится на панели инструментов Toolbox:

Свойства поля с календарем

Свойство Описание
CalendarBackColor Заливка (фон) календаря без заголовка.
CalendarForeColor Цвет шрифта чисел выбранного в календаре месяца.
CalendarTitleBackColor Заливка заголовка календаря и фон выбранной даты.
CalendarTitleForeColor Цвет шрифта заголовка (месяц и год) и выбранного в календаре числа.
CalendarTrailingForeColor Цвет шрифта чисел предыдущего и следующего месяца.
CheckBox В значении True отображает встроенный в DTPicker элемент управления CheckBox. По умолчанию – False.
ControlTipText Текст всплывающей подсказки при наведении курсора на DTPicker.
CustomFormat Пользовательский формат даты и времени. Работает, когда свойству Format присвоено значение dtpCustom (3).
Day (Month, Year) Задает или возвращает день (месяц, год).
DayOfWeek Задает или возвращает день недели от 1 до 7, отсчет начинается с воскресенья.
Enabled Возможность раскрытия календаря, ввода и редактирования даты/времени. True – все перечисленные опции включены, False – выключены (элемент управления становится серым).
Font Шрифт отображаемого значения в отформатированном поле элемента управления.
Format Формат отображаемого значения в поле элемента управления DTPicker, может принимать следующие значения: dtpCustom (3), dtpLongDate (0), dtpShortDate (1) (по умолчанию) и dtpTime (2).
Height Высота элемента управления DTPicker с нераскрытым календарем.
Hour (Minute, Second) Задает или возвращает часы (минуты, секунды).
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
MaxDate Максимальное значение даты, которое может быть выбрано в элементе управления (по умолчанию – 31.12.9999).
MinDate Минимальное значение даты, которое может быть выбрано в элементе управления (по умолчанию – 01.01.1601).
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с нуля.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
UpDown Отображает счетчик вместо раскрывающегося календаря. True – отображается SpinButton, False – отображается календарь (по умолчанию).
Value Задает или возвращает значение (дата и/или время) элемента управления.
Visible Видимость поля с календарем. True – DTPicker отображается на пользовательской форме, False – DTPicker скрыт.
Width Ширина элемента управления DTPicker с нераскрытым календарем.

DTPicker – это сокращение от слова DateTimePicker, не являющегося в VBA Excel ключевым словом, как и DatePicker.

Примеры кода VBA Excel с DTPicker

Программное создание DTPicker

Динамическое создание элемента управления DTPicker с помощью кода VBA Excel на пользовательской форме с любым именем:

Данный код должен быть размещен в модуле формы. Результат работы кода:

Применение свойства CustomFormat

Чтобы задать элементу управления DTPicker пользовательский формат отображения даты и времени, сначала необходимо присвоить свойству Format значение dtpCustom. Если этого не сделать, то, что бы мы не присвоили свойству CustomFormat, будет применен формат по умолчанию (dtpShortDate) или тот, который присвоен свойству Format.

В данном примере создается пользовательский формат для полей с календарем DTPicker1 и DTPicker2, размещенных на пользовательской форме, и отображаются в них текущие дата и время.

Результат работы кода:

Таблица специальных символов и строк, задающих пользовательский формат даты и времени (регистр символов имеет значение):

Символы и строки Описание
d День месяца из одной или двух цифр.
dd День месяца из двух цифр. К числу из одной цифры впереди добавляется ноль.
ddd Сокращенное название дня недели из двух символов (Пн, Вт и т.д.).
dddd Полное название дня недели.
h Час из одной или двух цифр в 12-часовом формате.
hh Час из двух цифр в 12-часовом формате. К часу из одной цифры впереди добавляется ноль.
H Час из одной или двух цифр в 24-часовом формате.
HH Час из двух цифр в 24-часовом формате. К часу из одной цифры впереди добавляется ноль.
m Минута из одной или двух цифр.
mm Минута из двух цифр. К минуте из одной цифры впереди добавляется ноль.
M Месяц из одной или двух цифр.
MM Месяц из двух цифр. К месяцу из одной цифры впереди добавляется ноль.
MMM Сокращенное название месяца из трех символов.
MMMM Полное название месяца.
s Секунда из одной или двух цифр.
ss Секунда из двух цифр. К секунде из одной цифры впереди добавляется ноль.
y Год из одной или двух последних цифр.
yy Год из двух последних цифр.
yyyy Год из четырех цифр.

Создание границ интервала дат

Простенький пример, как задать интервал дат с начала месяца до текущего дня с помощью двух элементов управления DTPicker:

Результат работы кода, запущенного 23.11.2020:

DTPicker – это сокращение от слова DateTimePicker, не являющегося в VBA Excel ключевым словом, как и DatePicker.

Источник

How to add Calendar, Date-Picker?

I need to add a Calendar Date Picker in Excel 2013.

I found that the MonthView and the DT Picker are no longer in the ActiveX menu and the links for a CAB file that supposedly contains these does not work. There are instruction documents, but they rely on a control that doesn’t exist.

I have an Excel Addin that does what I want, but I want to do this with VBA rather than install the Addin on every machine that will use this.

5 Answers 5

Once you have registered the mscomct2.ocx control (YOU WILL NEED TO REGISTER THIS FILE ON ALL COMPUTERS THAT WILL USE THIS WORKBOOK!), you can either add one of below controls in the Worksheet or in a UserForm:

  • Date and Time Picker (DTPicker), left/top of screenshots
  • MonthView, right/bottom of screenshots

WORKSHEET (ActiveX)

  1. In Developer tab, Controls group, click Insert, then bottom right button for More Controls.
  2. Scroll down and select Microsoft Date and Time Picker Control 6.0 (SP6) or Microsoft MonthView Control 6.0 (SP6) then click OK.
    |
  3. When you are out of Design Mode, clicking on the DTPicker control is like this, while the MonthView takes more space:
    |

UserForm

  1. In the Toolbox for the UserForm selected, right click on empty space of the Controls tab, click Additional Controls
  2. Scroll down and tick Microsoft Date and Time Picker Control 6.0 (SP6) or Microsoft MonthView Control 6.0 (SP6):
    |
  3. Now the controls are in your Controls tab to add on UserForms
  4. Default size of the controls on UserForm:

In either way, you will need to implement the actions when you click on these controls.

Источник

Fully Functional Dynamic Calendar Control in VBA

Ah, The complexities of automation! The versatile and multifaceted world of Excel VBA offers an array of tools and functionalities to streamline tasks and make life easier. Yet, despite its vast offerings, not all versions of Excel VBA come equipped with the desired calendar control, one that would allow for the selection of dates in a visually appealing manner, instead of the tedious manual input of dates into cells or text boxes. But fear not! For we shall embark on a journey, one that will unravel the mysteries of crafting a customized, dynamic calendar in Excel VBA using VBA User Forms and Command Buttons.

Step 1: Baffling Beginnings

Our journey begins with the creation of a User Form, a task achieved by navigating to the VBA editor and right-clicking on the ‘Project’ option in the Project Explorer, selecting ‘Insert’, followed by ‘User Form’. Voila! A new User Form will mysteriously appear, waiting to be customized to your whims and fancies.

Step 2: Commanding Conundrum

Next, we add a series of Command Buttons to the User Form, buttons that will act as our navigational tools, leading us through the calendar and enabling us to switch between months and years. And, to further confuse the matter, we add combo boxes, providing the option for the user to choose the month and year.

Step 3: Cryptic Code

With the controls in place, it’s time to delve into the code, to bring our dynamic calendar to life. To start, we write a function to generate the calendar based on the selected month and year, populating it with the correct number of days and illuminating the current date. And, as a bonus, we add a feature to highlight already existing dates in the text box or label by comparing the dates and marking them with a small star symbol, making the calendar even more user-friendly.

Watch the step-by-step video tutorials to learn the design and coding

Step 4: Calling the Calendar

Finally, with the dynamic calendar fully functional, we can summon it in our VBA project by using the ‘SelectedDate’ function. There are two methods to call this function:

Method 1: Call Calendar.SelectedDate(Me.TextBox1)

Method 2: Me.TextBox1.Value = Calendar.SelectedDate

The first method calls the calendar control and passes the value of the text box to the ‘SelectedDate’ function, while the second method calls the calendar control and assigns the selected date to the text box.

Move the Calendar control in from One to another VBA Project:

Just move this calendar form in your VBA project just drag it using mouse

Move Calendar to your VBA Project using Mouse

Bursting with Conclusions

And there you have it, a perplexing puzzle solved, a dynamic calendar crafted with the use of Excel VBA User Forms and Command Buttons. The calendar control, now at your beck and call, can be used in various VBA projects, and is easily summoned using the ‘SelectedDate’ function. And, with a few modifications, additional functionality, such as highlighting of existing dates or changes in style and appearance, can be added to further confuse and bewilder.

This Fully Functional Dynamic Calendar Control in VBA, we have designed to use in VBA project. You can use it for Excel Cells, Textbox, Label and Command Button etc. It is extremely easy to call this Calendar for your VBA Project. You can call this with two methods.

Источник

Понравилась статья? Поделить с друзьями:
  • Vba for application для excel
  • Vba for application word
  • Vba for access and excel
  • Vba excel цикл по датам
  • Vba excel цикл по всем строкам