2016-09-14 182 views
1

我知道這可能是一個簡單的問題,但我無法弄清楚這一點。當運行VBA的調試器時,第11行的第三個參數按預期顯示爲「9/13/2016」,但由於某些原因,start_d是「06/09/2016」?DateAdd返回值不正確

我曾嘗試將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 
+0

將系統日期格式更改爲dd-mm-yyyy。 – HA560

+0

在我的筆記本電腦上沒有dd-mm-yyyy選項,所以我使用了dd-MM-yy。 start_d仍然不正確:「06-09-2016」。爲什麼它甚至不是系統日期的格式......? –

+0

@ HA560我可以自定義它到您提出的日期,它仍然提出「06-09-2016」 –

回答

2

變化start_dDate類型,你可以用FormatCDate轉換做掉:

Dim start_d As Date 

它給你:

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 

編輯 看來你我們仍然有問題 - 讓我們嘗試一下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 

Dim today As Long 
today = Int(Now) 

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

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 
+0

我嘗試過這一點,爲了理智的緣故,我再次做了。我將start_d更改爲Date對象,並清除了cdate和格式化部分的代碼。唉...仍然沒有去... :( –

+0

我已經添加了一個編輯,使用一個長來保存日期作爲一個數字。你不應該需要,但希望它適用於你 – ThunderFrame

+0

如果它仍然doesn 't work - 你可以嘗試改變'start_d = DateAdd(「d」,-7,今天)''start_d = Int(Now) - 7' – ThunderFrame