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!
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.
1 / 1 / 0 Регистрация: 11.01.2019 Сообщений: 62 |
|
1 |
|
Excel 02.07.2021, 11:58. Показов 2930. Ответов 9
Добрый день форумчане!, подскажите пожалуйста, есть ли календарь в Excel 2019 ?
0 |
530 / 467 / 183 Регистрация: 11.12.2013 Сообщений: 2,459 |
|
02.07.2021, 14:17 |
2 |
Я у себя в Additional Controls выбирал Microsoft MonthView Control (Tools->AdditionalControls и в CheckListBox ищите Microsoft MonthView Control и ставите «галочку»), но это в excel 2013. И еще если соберетесь переносить свою книгу на другой комп то нужно будет устанавливать dll с Microsoft MonthView Control (если не установлена).
0 |
1 / 1 / 0 Регистрация: 11.01.2019 Сообщений: 62 |
|
02.07.2021, 15:55 [ТС] |
3 |
я об этом элементе знаю (Microsoft MonthView Control), но его в 2019 в Additional Controls нет, к сожалению.
0 |
530 / 467 / 183 Регистрация: 11.12.2013 Сообщений: 2,459 |
|
02.07.2021, 16:36 |
4 |
устанавливать MSCOMCT2.OCX не пробовали?
0 |
1 / 1 / 0 Регистрация: 11.01.2019 Сообщений: 62 |
|
02.07.2021, 16:53 [ТС] |
5 |
пробовал устанавливать по другому поводу, но нужный элемент не появился.
0 |
11482 / 3773 / 677 Регистрация: 13.02.2009 Сообщений: 11,145 |
|
02.07.2021, 17:22 |
6 |
есть много самописных календарей
0 |
1 / 1 / 0 Регистрация: 11.01.2019 Сообщений: 62 |
|
02.07.2021, 17:38 [ТС] |
7 |
согласен, самописные календари есть, но насколько их легитимно использовать?
0 |
ᴁ® 3070 / 1736 / 361 Регистрация: 13.12.2016 Сообщений: 5,938 Записей в блоге: 4 |
|
02.07.2021, 17:41 |
8 |
подскажите пожалуйста, есть ли календарь в Excel 2019 ? Нет
самописные календари есть, но насколько их легитимно использовать? Решать вам. Код везде открыт, достаточно уметь его читать.
0 |
811 / 465 / 181 Регистрация: 09.03.2009 Сообщений: 1,577 |
|
02.07.2021, 18:45 |
9 |
Вот еще календари.
0 |
1 / 1 / 0 Регистрация: 11.01.2019 Сообщений: 62 |
|
02.07.2021, 21:29 [ТС] |
10 |
Спасибо, есть выбор, попробую пару вариантов приладить к своей задаче.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
02.07.2021, 21:29 |
10 |
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
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
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
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
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.
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)) >= 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
Do you need a DatePicker Calendar in your Excel spreadsheets? Follow this quick and simple tutorial to find out how. (If you prefer video, scroll down to the bottom of the page!)
Step 1. Enable Developer Mode in Excel
- File
- Options
- Customize Ribbon
- Ensure Developer checkbox is enabled
[sibwp_form id=100]
Step 2. Setup DateTime Control box
- Microsoft Date and Time Picker Control
- Click on random cell to place control box
- Edit or remember the name box of the DateTime Picker, in this case, we will leave it as DatePicker1
- Right click on DateTime Control box
- DTPicker Object
- Properties
- Enable CheckBox
Step 3. Copy the Visual Basic code
To assign column A as a DatePicker, copy the following code:
Code language: PHP (php)
Private Sub Worksheet_SelectionChange(ByVal Target As Range) With Sheet1.DTPicker1 .Height = 20 .Width = 20 If Not Intersect(Target, Range("A:A")) Is Nothing Then .Visible = True .Top = Target.Top .Left = Target.Offset(0, 1).Left .LinkedCell = Target.Address Else .Visible = False End If End With End Sub
- Right click the DateTime Control box
- View Code
- Replace all of the existing code with the code from above
- Close the Visual Basic editor
- Deselect Design Mode
- Click on any cell to remove DateTime Control box
- Click on any cell in Column A to add a Date
Congratulations!
Important: Make sure that when you save the spreadsheet, you “Save As: Macro enabled workbook”
How to have multiple columns with DatePickers
The above steps only work for single columns, or columns that are right next to each other. If you wanted the DatePicker column to be in column B instead, then you would change the line
If Not Intersect(Target, Range("A:A")) Is Nothing Then
Code language: JavaScript (javascript)
to
Code language: JavaScript (javascript)
If Not Intersect(Target, Range("B:B")) Is Nothing Then
Or if you wanted it from Column E to Column G, then you would change that line to
Code language: JavaScript (javascript)
If Not Intersect(Target, Range("E:G")) Is Nothing Then
However, if you need a DatePicker in two or more non-adjacent columns, then you will need a separate DatePicker (each with a separate name in the Name Box) for each non-adjacenet group. For example, let’s say we need column A, B, E, F, and H to all be DatePickers. We would need to perform the above steps 3 separate times for 3 separate DatePickers.
- 1 for columns A, B
- 1 for columns E, F
- 1 for column H
The steps will be very similar, but the code will be:
Code language: PHP (php)
Private Sub Worksheet_SelectionChange(ByVal Target As Range) With Sheet1.DTPicker1 .Height = 20 .Width = 20 If Not Intersect(Target, Range("A:B")) Is Nothing Then .Visible = True .Top = Target.Top .Left = Target.Offset(0, 1).Left .LinkedCell = Target.Address Else .Visible = False End If End With With Sheet1.DTPicker2 .Height = 20 .Width = 20 If Not Intersect(Target, Range("E:F")) Is Nothing Then .Visible = True .Top = Target.Top .Left = Target.Offset(0, 1).Left .LinkedCell = Target.Address Else .Visible = False End If End With With Sheet1.DTPicker3 .Height = 20 .Width = 20 If Not Intersect(Target, Range("H:H")) Is Nothing Then .Visible = True .Top = Target.Top .Left = Target.Offset(0, 1).Left .LinkedCell = Target.Address Else .Visible = False End If End With End Sub
Important legal notice: This post contains affiliate links. We are compensated for many of our product recommendations. Pragmatic Ways is a participant in the Amazon Associates affiliate program, as well as other affiliate programs. While we are always careful to only recommend the products we use and recommend, we want to be open and transparent about our relationship with companies we recommend.
Adam Allard
Hi, I’m Adam Allard. I’m a Full Stack Software Engineer for Northrop Grumman creating web applications for the DoD. At this time I’m primarily working with Java and Angular based applications, although I have some years of experience in various languages and frameworks from previous jobs where I dabbled with Python & Django, C# & Xamarin, PHP, and Bootstrap. My hobbies include time with my family, wondering when the Green Bay Packers will win their next Super Bowl, drinking over-priced beer, and of course learning and teaching.
Recent Posts
Unit Conversions
The tables below are all the unit conversion factors used in the Unit Converter App tutorial, where we walked through together building out a JavaFX and SceneBuilder interface.
Click here to…
How to add JavaFX to Eclipse (the easy way)
Step 1. Download JavaFX
Go to https://gluonhq.com/products/javafx/ and download the appropriate SDK for your operating system. Make sure you download the SDK and make sure you choose the correct…