VBA更改日期的具体位
问题描述:
我目前有一个预先写好日期的电子表格,以dd/mm/yyyy格式排序,但我希望能够更改整个工作表,以便当我从一个drop中选择一个月下拉列表中,它会更改所有日期,以便从第1个到第31个开始,但仅使用visual basic更改月份。我可以用它来设定具体日期,VBA更改日期的具体位
Range("C3") = Format(DateSerial(Year:=2005, Month:=2, Day:=3), "mm-dd-yyyy")
但是,使用这样的事情,例如
Range("C3") = Format(DateSerial(Month:=5), "mm-dd-yyyy")
答
你可以做这样的事情,我可以改变只包括月:
Function MakeDates(startDate As Date) As Date()
Dim myDates() As Date, myYear As Integer, myMonth As Integer, daysInMonth As Integer
Dim firstOfMonth As Date, firstOfNextMonth As Date, d As Integer
myYear = Year(startDate)
myMonth = Month(startDate)
firstOfMonth = DateSerial(myYear, myMonth, 1)
firstOfNextMonth = DateSerial(myYear, myMonth + 1, 1)
daysInMonth = DateDiff("d", firstOfMonth, firstOfNextMonth)
ReDim myDates(daysInMonth - 1)
For d = 1 To daysInMonth
myDates(d - 1) = DateSerial(myYear, myMonth, d)
Next d
MakeDates = myDates
End Function
那么你可以这样称呼它
Dim d
d = MakeDates(#2/1/2014#)
Range("A1").Resize(rowsize:=31).Value = ""
Range("A1").Resize(rowsize:=UBound(d) + 1) = WorksheetFunction.Transpose(d)
倒数第二行将为您删除多余的日期。
您应该将范围格式化为日期。你可以在代码中做到这一点,或只是在Excel中做一次。后者可能更容易。
'所以他们保持从第一到第三十一'如果你将12月31日更改为二月份会发生什么? –
这将是一个稍后的脚本位,我将删除月份范围以外的部分。 –