DateAdd返回值不正确

时间:2016-09-14 04:11:58

标签: vba

我知道这可能是一个简单的问题,但我无法弄清楚这一点。在为VBA运行调试器时,第11行的第三个参数显示为" 9/13/2016"正如所料,但start_d是" 06/09/2016"出于某种原因???

我尝试将start_d设置为字符串和Date对象,两者都产生相同的结果。我想要的是start_d是当前日期之前的7天。

Sub addData(lastRow As Integer, lab() As String, c() As String, IP() As String, usage() As String, fName As String)
Dim reportWeek As Integer
Dim numWeeks As Integer
Dim monthWeek As Integer
Dim start_d As Date ' As String UPDATED
Dim thisYear As String
Dim thisMonth As String
Dim thisDay As String

' the reports run every monday
start_d = DateAdd("d", -7, Date)
'start_d = Format(start_d, "dd/mm/yyyy") UPDATED 

thisYear = year(start_d) 'year(CDate(start_d)) UPDATED
thisMonth = month(start_d) 'month(CDate(start_d)) UPDATED
thisDay = day(start_d) 'day(CDate(start_d)) UPDATED

reportWeek = weekNum
monthWeek = getWeekOfMonth(CDate(start_d))
numWeeks = weekCount(thisYear, thisMonth)

Debug.Print reportWeek & monthWeek & numWeeks & thisYear & thisMonth & thisDay
End Sub

1 个答案:

答案 0 :(得分:2)

gen(length, depth+1) 更改为start_d类型,您可以取消DateFormat次转化:

CDate

这给了你:

Dim start_d As Date

修改 看起来你还有问题 - 让我们尝试使用Long表示日期:

Sub addData()
Dim reportWeek As Integer
Dim numWeeks As Integer
Dim monthWeek As Integer
Dim start_d As Date
Dim thisYear As String
Dim thisMonth As String
Dim thisDay As String

' the reports run every monday
start_d = DateAdd("d", -7, Date)

thisYear = Year(start_d)
thisMonth = Month(start_d)
thisDay = Day(start_d)

reportWeek = WeekNum
monthWeek = getWeekOfMonth(start_d)
numWeeks = weekCount(thisYear, thisMonth)

Debug.Print reportWeek & monthWeek & numWeeks & thisYear & thisMonth & thisDay
End Sub