VBA更改具体的日期位

时间:2014-03-27 11:40:08

标签: excel vba excel-vba

我目前有一个带有预先写入日期的电子表格,以dd / mm / yyyy格式排序,但我希望能够更改整个工作表,以便当我从下拉列表中选择一个月时,它会更改所有日期,所以他们从1日开始到31日开始,但只有月份变化,使用visual basic。我可以用它来设置具体的日期,

Range("C3") = Format(DateSerial(Year:=2005, Month:=2, Day:=3), "mm-dd-yyyy")

但是我可以使用类似的东西来改变月份,例如

Range("C3") = Format(DateSerial(Month:=5), "mm-dd-yyyy")

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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中执行一次。后者可能更容易。