ExcelのDateTime.DateAdd VBA関数を使用して日付の列を作成しています。次のコードを使用すると、時刻が深夜になると、期待どおりに変更されません。VBA DateAddが正常に動作しない
Sub test()
Dim i As Integer
Dim currentDate As Date
With ThisWorkbook.Sheets(1)
.Cells.Clear
.Cells(1, 1) = "DateTime"
.Cells(1, 2) = "Day"
currentDate = CDate("10/3/2016 11:59:30 PM")
For i = 1 To 10
.Cells(i + 1, 1) = currentDate
.Cells(i + 1, 2) = DateTime.Day(currentDate)
currentDate = DateTime.DateAdd("s", 5, currentDate)
Next i
.Columns(1).NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
End With
End Sub
出力:
- のDateTime |日
- 10/3/2016 11:59:30 PM | 3
- 10/3/2016 11:59:35 PM | 3
- 10/3/2016 11:59:40 PM | 3
- 10/3/2016 11:59:45 PM | 3
- 10/3/2016 11:59:50 PM | 3
- 10/3/2016 11:59:55 PM | 3
- 10//2016 12:00:00 AM | (日の値が一致しません)
- 10/4/2016 12:00:05 AM | 4
- 10/4/2016 12:00:10 AM | 4
- 10/4/2016 12:00:15 AM | 4
数値形式を軍用時間に変更すると、同様の結果が得られます。チャートのx値として出力日付を使用すると、チャートは '不正な'曜日値を使用します。ただし、コードの開始時刻を10/3/2016 11:59:45 PMに変更すると、予想通りに日が変更されます。間違ったことをやっているのですか、あるいはVBAで日付に時間を追加するための、もう少し安定した方法がありますか?
EDIT:mrbungleとコミンテルンによって提供さ
優れた回避策。彼らはどちらも同じ最終結果を達成しますが、私はmrbungleの方法がほんの髪の毛が好きです。なぜなら、量を無視しても値を変更することを避けるからです。
は代替案を要約すると:Sub test()
Dim i As Integer
Dim currentDate As Date
With ThisWorkbook.Sheets(1)
.Cells.Clear
.Cells(1, 1) = "DateTime"
.Cells(1, 2) = "Day"
currentDate = CDate("10/3/2016 11:59:30 PM")
For i = 1 To 10
.Cells(i + 1, 1) = CStr(currentDate) ' mrbungle's method
.Cells(i + 1, 1) = currentDate + 0.000000001 ' Comintern's method
.Cells(i + 1, 2) = DateTime.Day(currentDate)
currentDate = DateTime.DateAdd("s", 5, currentDate)
Next i
.Columns(1).NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
End With
End Sub