[英]Populate date cells based on one cell's value?
I would like the ability for the user to enter a year (eg "2013") in cell D1 and press a button that fires off a macro. 我希望用户能够在单元格D1中输入年份(例如“ 2013”)并按下触发宏的按钮。 This macro will automatically assign a function to cells D2-O2 (one cell for each month in the year) that converts these cells to actual date types.
此宏将自动为D2-O2单元(一年中每个月一个单元)分配一个函数,将这些单元转换为实际日期类型。
For instance, cell D2's value would be =DATE(2013, 1, 1)
, signifying that this cell represents January 1st of 2013. Similarly, cell E2's value would be =DATE(2013, 2, 1)
, F2's value would be =DATE(2013, 3, 1)
, etc. 例如,单元格D2的值为
=DATE(2013, 1, 1)
2013,1,1 =DATE(2013, 1, 1)
,表示此单元格代表2013年1月1日。类似地,单元格E2的值为=DATE(2013, 2, 1)
,F2的值为=DATE(2013, 3, 1)
等
The following is my pseudo code, could you please help me convert this to actual VBA? 以下是我的伪代码,请您帮我将其转换为实际的VBA吗?
var myYear = the value of cell D1
cell D2 value is =DATE(2013,1,1)
cell E2 value is =DATE(2013,2,1)
cell F2 value is =DATE(2013,3,1)
cell G2 value is =DATE(2013,4,1)
cell H2 value is =DATE(2013,5,1)
cell I2 value is =DATE(2013,6,1)
cell J2 value is =DATE(2013,7,1)
cell K2 value is =DATE(2013,8,1)
cell L2 value is =DATE(2013,9,1)
cell M2 value is =DATE(2013,10,1)
cell N2 value is =DATE(2013,11,1)
cell O2 value is =DATE(2013,12,1)
Thanks 谢谢
Try this: 尝试这个:
Sub FillYear()
YearNum = Cells(1, 4) ' Cell D1
For MonthNum = 1 To 12
Cells(2, MonthNum + 3).Value = DateSerial(YearNum, MonthNum, 1)
Next
End Sub
UPDATE: 更新:
If you want the date values to be a formula, so that the dates change if the user changes the year, change the line inside the For Loop
to be: 如果希望日期值成为公式,以便用户更改年份时日期也可以更改,请将
For Loop
内的行更改为:
Cells(2, MonthNum + 3).Formula = "=Date(R1C4," & MonthNum & ", 1)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.