思路比较简单,样式也单一,丑了点。
采用宏和时间函数,计算单元格偏移量,进行单元格填充。
Sub GenerateYearCalendar()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") ' 更改为你使用的表名
Dim year As Integer
year = InputBox("请输入年份 (如2025):")
If Not IsNumeric(year) Or year < 1900 Or year > 2100 Then
MsgBox "无效的年份", vbExclamation
Exit Sub
End If
' 清除现有内容
ws.Cells.Clear
' 设置列宽和行高
ws.Columns.ColumnWidth = 10
ws.Rows.RowHeight = 20
' 初始化起始位置
Dim startRow As Integer, startCol As Integer
startRow = 0
startCol = 1
' 循环生成每个月的日历
Dim month As Integer
For month = 1 To 12
Call GenerateMonthCalendar(ws, year, month, startRow, startCol)
' 更新下一个月的日历起始位置
startCol = 1
Next month
End Sub
Sub GenerateMonthCalendar(ws As Worksheet, year As Integer, month As Integer, ByRef startRow As Integer, ByRef startCol As Integer)
' 设置月份标题
startRow = startRow + 1
ws.Cells(startRow, 1).Value = year & "年" & month & "月"
ws.Range(ws.Cells(startRow, startCol), ws.Cells(startRow, startCol + 6)).MergeCells = True
ws.Range(ws.Cells(startRow, startCol), ws.Cells(startRow, startCol + 6)).HorizontalAlignment = xlCenter
ws.Range(ws.Cells(startRow, startCol), ws.Cells(startRow, startCol + 6)).VerticalAlignment = xlCenter
startRow = startRow + 1
' 设置星期几的标题
ws.Cells(startRow, 1).Value = "一"
ws.Cells(startRow, 2).Value = "二"
ws.Cells(startRow, 3).Value = "三"
ws.Cells(startRow, 4).Value = "四"
ws.Cells(startRow, 5).Value = "五"
ws.Cells(startRow, 6).Value = "六"
ws.Cells(startRow, 7).Value = "日"
startRow = startRow + 1
' 计算第一个日期的位置
Dim firstDay As Date
firstDay = DateSerial(year, month, 1)
Dim startColDate As Integer
startColDate = Weekday(firstDay, vbMonday) - 1
' 设置日期
Dim lastDay As Date
lastDay = DateSerial(year, month + 1, 0)
Dim row As Integer, col As Integer
row = startRow
col = startCol + startColDate
For i = 1 To Day(lastDay)
ws.Cells(row, col).Value = i
col = col + 1
' 进行换行
If col > 7 Then
col = 1
row = row + 1
End If
Next i
' 更新起始行
startRow = row
End Sub
标签:Cells,日历,excel,生成,startRow,startCol,ws,year,Integer
From: https://www.cnblogs.com/GISyunqi/p/18675611