Excel for Microsoft 365, Excel 2019, Excel 2016, Excel 2013, Excel 2010, Excel 2007, Excel 2003
Résumé
Cet article contient un exemple de macro Microsoft Visual Basic pour Applications (procédure Sub) qui vous invite à entrer le mois et l’année et crée un calendrier mensuel à partir d’une feuille de calcul.
Résolution
Note
Microsoft fournit des exemples de programmation à titre d’illustration uniquement, sans garantie expresse ou implicite. Cela inclut, sans y être limité, les garanties implicites de commercialisation et d’adaptation à un but en particulier. Cet article considère que vous connaissez le langage de programmation présenté et les outils utilisés pour créer et déboguer des procédures. Les techniciens du Support technique Microsoft peuvent vous expliquer les fonctionnalités d’une procédure particulière, mais ils ne peuvent pas modifier les exemples en vue de vous fournir des fonctionnalités supplémentaires ou de créer des procédures répondant à vos besoins spécifiques.
Pour créer le calendrier, procédez comme suit.
Microsoft Excel 2003
Créez un classeur.
Dans le menu Outils, pointez sur Macro, puis cliquez sur Visual Basic Editor.
Dans le menu Insertion, cliquez sur Module.
Coller le script Visual Basic pour Applications de la section « Exemple de procédure Visual Basic » dans la feuille de module.
Dans le menu Fichier, cliquez sur Fermer et retourner à Microsoft Excel.
Sélectionnez l’onglet Feuille1.
Dans le menu Outils, pointez sur Macro puis sélectionnez Macros.
Cliquez sur CalendarMaker puis sur Exécuter pour créer le calendrier.
Microsoft Excel 2007 ou version ultérieure
Créez un classeur.
Dans le ruban Développeur, cliquez sur Visual Basic.
Dans le menu *Insertion, cliquez sur Module.
Coller le script Visual Basic pour Applications de la section « Exemple de procédure Visual Basic » dans la feuille de module.
Dans le menu Fichier, cliquez sur Fermer et retourner à Microsoft Excel.
Sélectionnez l’onglet Feuille1.
Dans le ruban *Développeur, cliquez sur Macros.
Cliquez sur CalendarMaker puis sur *Exécuter pour créer le calendrier.
Note
Si le ruban Développeur ne s’affiche pas, accédez aux Options Excel et activez-le. Dans Excel 2007, l’option est disponible dans le menu Populaire. Dans Excel 2010, l’option est disponible dans le menu Personnaliser le ruban.
Exemple de procédure Visual Basic
VB
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.OnErrorGoTo 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 = ""ThenExitSub' 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) <> 1Then
StartDay = DateValue(Month(StartDay) & "/1/" & _
Year(StartDay))
EndIf' 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 = 35EndWith' 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 = 20EndWith' 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 = 21EndWith' 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.SelectCase DayofWeek
Case1
Range("a3").Value = 1Case2
Range("b3").Value = 1Case3
Range("c3").Value = 1Case4
Range("d3").Value = 1Case5
Range("e3").Value = 1Case6
Range("f3").Value = 1Case7
Range("g3").Value = 1EndSelect' Loop through range a3:g8 incrementing each cell after the "1"' cell.ForEach cell In Range("a3:g8")
RowCell = cell.Row
ColCell = cell.Column
' Do if "1" is in first column.If cell.Column = 1And cell.Row = 3Then' Do if current cell is not in 1st column.ElseIf cell.Column <> 1ThenIf cell.Offset(0, -1).Value >= 1Then
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.ExitForEndIfEndIf' Do only if current cell is not in Row 3 and is in Column 1.ElseIf cell.Row > 3And cell.Column = 1Then
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.ExitForEndIfEndIfNext' Create Entry cells, format them centered, wrap text, and border' around days.For x = 0To5
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 = FalseEndWith' Put border around the block of dates.With Range("A3").Offset(x * 2, 0).Resize(2, _
7).Borders(xlLeft)
.Weight = xlThick
.ColorIndex = xlAutomatic
EndWithWith Range("A3").Offset(x * 2, 0).Resize(2, _
7).Borders(xlRight)
.Weight = xlThick
.ColorIndex = xlAutomatic
EndWith
Range("A3").Offset(x * 2, 0).Resize(2, 7).BorderAround _
Weight:=xlThick, ColorIndex:=xlAutomatic
NextIf 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.ExitSub' 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 = ""ThenExitSubResumeEndSub
Vous pouvez ajouter du code pour personnaliser le calendrier afin qu’il réponde à vos besoins. Insérez des lignes supplémentaires à l’écran pour chaque jour ou redimensionnez l’écran pour afficher tout le calendrier en fonction de la taille et de la résolution d’écran.
Tunjukkan bahwa Anda memiliki keterampilan yang diperlukan untuk mendapatkan hasil maksimal dari Excel 2016 dengan mendapatkan sertifikasi Microsoft Office Specialist (MOS).