2017-02-22 36 views
1

我想在2018年全年這樣做,當我運行我的代碼時,我得到了2017年。這裏是我的代碼如下複製一年的Excel表格

Sub MakeSheetForEachDay() 
'Will copy the sheet named "START" and rename as 
'as a date, 1-Jan, 2-Jan, etc. 
' 
    Dim wsStart As Worksheet 
    Dim strDate As String 
    Dim mth As Long, dy As Long 

    Set wsStart = Sheets("START") 
    For mth = 1 To 12 
     For dy = 1 To Day(DateSerial(Year(2018), mth + 1, 1) - 1) 
      strDate = Format(DateSerial(Year(2018), mth, dy), "ddd mmm d") 
      wsStart.Copy after:=Sheets(Sheets.Count) 
      Sheets(Sheets.Count).Name = strDate 
     Next dy 
    Next mth 
End Sub 
+0

爲什麼年()? – Pierre

回答

2

簡短的回答不使用Year(2018)只是使用DateSerial(2018, mth + 1, 1)

如果你看一下documentation for year你會看到它定義爲

Public Function Year(ByVal DateValue As DateTime) As Integer 

這意味着當Year(2018)評估它必須將整數2018轉換爲DateTime。它通過將2018天添加到給你7/10/1905的時代來做到這一點。所以Year(2018)返回1905.

恰好如此,Format(DateSerial(2017, mth, dy), "ddd mmm d")Format(DateSerial(1905, mth, dy), "ddd mmm d")返回相同的值,因爲1905年和1901年1月1日都是星期日。這就是爲什麼你的輸出困惑Format(DateSerial(Year(2018), mth, dy), "ddd mmm d")