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

如何实现Excel宏:输入日期后自动填充至当月月末每日日期

Excel宏:从指定日期逐列填充至当月月末

以下是实现需求的VBA代码,能自动识别不同月份的天数,从用户输入的日期开始,在当前单元格起逐列填充递增日期,直到当月最后一天:

Sub FillDatesToMonthEnd()
    Dim dtStartDate As Date
    Dim dtCurrentDate As Date
    Dim dtMonthEnd As Date
    Dim currentCell As Range
    
    ' 获取用户输入的日期,默认显示当前日期
    On Error Resume Next
    dtStartDate = InputBox("请输入起始日期:", "日期输入", Date)
    ' 处理用户取消输入或无效日期的情况
    If Err.Number <> 0 Or dtStartDate = 0 Then
        MsgBox "输入无效,已取消操作。"
        Exit Sub
    End If
    On Error GoTo 0
    
    ' 计算当月最后一天,自动适配不同月份天数
    dtMonthEnd = DateSerial(Year(dtStartDate), Month(dtStartDate) + 1, 0)
    dtCurrentDate = dtStartDate
    Set currentCell = ActiveCell
    
    ' 循环填充日期直到月末
    Do While dtCurrentDate <= dtMonthEnd
        currentCell.Value = dtCurrentDate
        ' 日期加1,单元格右移一列
        dtCurrentDate = dtCurrentDate + 1
        Set currentCell = currentCell.Offset(0, 1)
    Loop
End Sub

关键逻辑说明:

  • 月末日期计算:DateSerial(Year(dtStartDate), Month(dtStartDate) + 1, 0)是VBA中计算当月月末的标准写法,通过将目标月份设为当前月+1、日期设为0,会自动回退到当前月的最后一天,完美适配28/29/30/31天的不同月份。
  • 循环填充:通过Do While循环,从起始日期开始逐个填充单元格,每次完成后日期加1、单元格右移一列,直到日期超过月末时停止。
  • 异常处理:加入了对用户取消输入、无效日期的判断,避免宏运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:37:06