首页 > 解决方案 > VBA 宏返回连续的月末,最好不循环

问题描述

我正在尝试使用 VBA 自动化重复过程。作为该过程的一部分,我需要在 Excel 工作表中填充一系列单元格,其中包含先前在代码中计算的数个月的连续月末。

我尝试了 Dick Kusleika 在此线程中提出的解决方案: VBA 宏返回连续的月末,这看起来非常优雅和简单,并且不涉及循环遍历每个单元格以填充日期。不幸的是,它产生了编译错误。

这是我试过的代码:

Dim xData As Worksheet
Dim xDLastRow As Long, xDProjCol As Long
Dim xSYear As Long, xMonths As Long

'Code that defines my variables and does other stuff

    With xData.Range(Cells(xDLastRow + 1, xDProjCol + 2))
        .Value = DateSerial(xSYear, 1, 31)
        .AutoFill.Resize(xMonths, 1), xlFillMonths  'ERROR HERE
    End With

'Other code...

在 Autofill.Resize 代码行上,我得到“编译错误:预期:=”

我的偏好是找到一个非循环的解决方案,因为这已经是一个更大的循环的一部分,并且会运行多次。如果有一个理想的快速自动填充解决方案。

编辑: Ahmed Abdelhameed提出的更正使代码能够正常工作。修改后的代码是:

Dim xData As Worksheet
Dim xDLastRow As Long, xDProjCol As Long
Dim xSYear As Long, xMonths As Long

'Code that defines my variables and does other stuff

    With xData.Cells(xDLastRow + 1, xDProjCol + 2)     'REMOVED .Range(
        .Value = DateSerial(xSYear, 1, 31)
        .AutoFill .Resize(xMonths, 1), xlFillMonths    'ADDED SPACE BEFORE .Resize
    End With

'Other code...

标签: excelvba

解决方案


您可以使用 EOMONTH 函数填充范围并将公式结果恢复为其值。

With xData.Cells(xDLastRow + 1, xDProjCol + 2).Resize(xMonths, 1)
    .Formula = "=eomonth(date(" & xSYear & ", 1, 1), row(1:1)-1)"
    .Value = .Value
    .NumberFormat = "mm/dd/yyyy_)"
End With

推荐阅读