You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动生成指定月份的所有日期行?附示例表格

用Excel宏自动生成指定月份日期表格

当然可以用Excel宏实现这个需求,以下是具体的实现步骤和代码:

实现步骤

  • 打开Excel,按下Alt + F11打开VBA编辑器
  • 插入新模块:右键点击左侧项目窗口中的工作簿名称 → 插入 → 模块
  • 将下方宏代码粘贴到模块中
  • 运行宏,输入目标年份和月份即可生成表格

宏代码示例

Sub GenerateMonthlyDates()
    Dim targetYear As Integer
    Dim targetMonth As Integer
    Dim startDate As Date
    Dim endDate As Date
    Dim currentDate As Date
    Dim rowNum As Integer
    
    ' 获取用户输入的年份和月份
    targetYear = InputBox("请输入年份(如2022):")
    targetMonth = InputBox("请输入月份(1-12):")
    
    ' 计算当月的第一天和最后一天
    startDate = DateSerial(targetYear, targetMonth, 1)
    endDate = DateSerial(targetYear, targetMonth + 1, 0)
    
    ' 清空当前工作表已有数据(保留表头)
    Rows("2:" & Rows.Count).ClearContents
    
    ' 设置表头
    Range("A1").Value = "ROW"
    Range("B1").Value = "DATE"
    Range("C1").Value = "DAY"
    Range("D1").Value = "NOTE"
    
    ' 格式化表头
    Range("A1:D1").Font.Bold = True
    Range("A1:D1").HorizontalAlignment = xlCenter
    
    ' 填充日期数据
    rowNum = 2
    currentDate = startDate
    Do While currentDate <= endDate
        Range("A" & rowNum).Value = rowNum - 1 ' 行号从1开始
        Range("B" & rowNum).Value = currentDate
        Range("B" & rowNum).NumberFormat = "yyyy/mm/dd" ' 设置日期格式
        Range("C" & rowNum).Value = Format(currentDate, "aaaa") ' 显示中文星期
        rowNum = rowNum + 1
        currentDate = currentDate + 1
    Loop
    
    ' 自动调整列宽
    Columns("A:D").AutoFit
    
    MsgBox "指定月份日期表格已生成完成!", vbInformation
End Sub

使用说明

  • 运行宏后,会弹出输入框让你输入年份和月份
  • 生成的表格会自动填充行号、日期、中文星期,备注列留空可手动填写
  • 代码会自动清空表头以下的旧数据,避免重复内容

内容的提问来源于stack exchange,提问作者Marcello Impastato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:20:32