excel - 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...
解决方案
您可以使用 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
推荐阅读
- javascript - 选择较短的选项时,HTML 下拉菜单更改大小
- javascript - 如何使用 Slack API 删除特定频道中的任何消息?
- php - 试图创建一个动态的 swiper
- swiftui - TabView 内的 NavigationView 默认进入下一页
- angular - 执行多个 UserRole 检查
- javascript - 将字体样式从对象映射映射到 map() 的正确语法
- ios - 运行 ios 应用程序时出现 Cocoapods 错误,导致 pod install 出错
- selenium - 抓取angellist启动数据
- idris - 构造函数中的表达式时,“MkFoo 的返回类型必须在 Foo 中”
- javascript - React Router 与特定的 React 组件不兼容