Insert each date record for current month in Access table using VBA

你离开我真会死。 提交于 2019-12-02 09:01:18

The following expression will give you an integer, the number of days in the current month:

Day(DateSerial(Year(Date()), Month(Date())+1, 0))

This is the zeroth day of the following month, which is the last day of the current month. This expression will still work if moving from December to January.

Store this in a variable, say lastDay then use a loop, For x = 1 To lastDay to perform the inserts.

Within the loop, this expression

DateSerial(Year(Date()), Month(Date()), x)

will give you the dates 1/5/2016, 2/5/2016,.., 31/5/2016.

You should also surround the dates with date delimiters # when inserting. Combine this with ISO formatting of the date yyyy-mm-dd (so that months won't be interpreted as days):

VALUES (#" & Format(dtValue, "yyyy-mm-dd") & "#)"

where dtValue is the date you've just formed using the previous DateSerial expression.

You can create a table containing every possible day number

[DayOfMonth]

dd
--
 1
 2
 3
...
30
31

and then just use a query like this to generate one row for each day in the current month

SELECT DateSerial(Year(Date()), Month(Date()), dd) AS IDate
FROM DayOfMonth
WHERE Month(DateSerial(Year(Date()), Month(Date()), dd)) = Month(Date())

To use it as an INSERT query would be

INSERT INTO tbl_ShipOrders (IDate)
SELECT DateSerial(Year(Date()), Month(Date()), dd) AS IDate
FROM DayOfMonth
WHERE Month(DateSerial(Year(Date()), Month(Date()), dd)) = Month(Date())

Please, see below code and read comments:

Option Explicit

Sub Command0_Click()
Dim startDate As Date
Dim endDate As Date
Dim curDate As Date

'get first day from current date
startDate = GetFirstDayInMonth(Date)
'get last day from startDate
endDate = GetLastDayInMonth(startDate)
'loop through the dates
For curDate = startDate To endDate
    'here call the procedure to insert data
Next

End Sub

'function to return first date in the month
Function GetFirstDayInMonth(dCurDate As Date) As Date

    GetFirstDayInMonth = DateSerial(Year(dCurDate), Month(dCurDate), 1)

End Function

'return last date in the month
Function GetLastDayInMonth(dCurDate As Date) As Date

    GetLastDayInMonth = DateSerial(Year(dCurDate), Month(dCurDate) + 1, 1 - 1)

End Function

Here's a fancy query that will return a month's dates:

SELECT DISTINCT 
    10 * Abs([Deca].[id] Mod 10) + Abs([Uno].[id] Mod 10) AS Id, 
    DateAdd("d",[Id], DateSerial(Year(DateOfMonth), Month(DateOfMonth), 1)) AS [Date]
FROM 
    msysobjects AS Uno, 
    msysobjects AS Deca
WHERE 
    (10*Abs([Deca].[id] Mod 10) + Abs([Uno].[id] Mod 10)) < Day(DateSerial(Year(DateOfMonth), Month(DateOfMonth)+1, 0))

That said, I would write a loop adding records to a recordset using VBA, not the slow SQL call of yours.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!