使用excel生成简单的日历

Posted on   云起  阅读(25)  评论(0编辑  收藏  举报

思路比较简单,样式也单一,丑了点。
采用宏和时间函数,计算单元格偏移量,进行单元格填充。

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
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

随笔 - 119, 文章 - 0, 评论 - 3, 阅读 - 4025

Copyright © 2025 云起
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示