如何在vba中更改日期

时间:2016-06-20 06:43:13

标签: excel-vba date vba excel

我想根据某些条件更改日期。如果当天超过15天,则应为15天,如果小于15天则应为1天。 我写的代码是:

date1 = ActiveSheet.Cells(k, 2).Value
tempArr = Split(date1, "/")
If (tempArr(2) < 15) Then
    reqdDate = tempArr(0) + "/" + tempArr(1) + "/01"
Else
    reqdDate = tempArr(0) + "/" + tempArr(1) + "/15"
End If

对于我的系统,它的工作正常,因为日期格式是yyyy / mm / dd。但对于其他系统而言,随着系统日期的不同而崩溃。如何实现这个功能。我试图改变日期的格式

tempDate = Format(date1, "yyyy/mm/dd")

但即使这样也行不通。

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:

Dim d, reqdDate As Date
d = CDate(ActiveSheet.Cells(k, 2).Value)
If (Day(d) < 15) Then
    reqdDate = DateSerial(Year(d), Month(d), 1)
Else
    reqdDate = DateSerial(Year(d), Month(d), 15)
End If

我建议您使用Date-Type而不是字符串。所以你可以使用内置函数。

拥有操纵日期后,您可以根据需要对其进行格式化