使用 VBA 在 Access 表中插入当前月份的每个日期记录

Posted

技术标签:

【中文标题】使用 VBA 在 Access 表中插入当前月份的每个日期记录【英文标题】:Insert each date record for current month in Access table using VBA 【发布时间】:2016-05-29 09:27:16 【问题描述】:

我是 VBA 编程新手。我设计了一种形式,其中有一个按钮。单击此按钮后,我想在具有一个日期列的表中插入记录。虚拟记录的数量应等于当月的天数。如果月份是 2016 年 5 月,则将插入日期为 2016 年 1 月 5 日的记录, 2/5/2016.......31/5/2016 就这样。

提前致谢。

Private Sub Command0_Click()
    Dim strQuery As String
    Dim currDateTime As Date
    currDateTime = Now()
    strQuery = "INSERT INTO tbl_ShipOrders (IDate ) VALUES (" & currDateTime & " )"
    CurrentDb.Execute (strQuery)
End Sub

【问题讨论】:

使用for...next循环。 【参考方案1】:

以下表达式将为您提供一个整数,即当月的天数:

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

这是下个月的第 0 天,也就是当月的最后一天。如果从 12 月移至 1 月,此表达式仍然有效。

将其存储在变量中,例如 lastDay,然后使用循环 For x = 1 To lastDay 来执行插入操作。

在循环中,这个表达式

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

将为您提供日期 2016 年 1 月 5 日、2016 年 2 月 5 日、..、2016 年 5 月 31 日。

您还应该在插入时用日期分隔符 # 将日期括起来。将此与日期yyyy-mm-dd 的 ISO 格式结合起来(这样月份就不会被解释为天):

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

其中 dtValue 是您刚刚使用之前的 DateSerial 表达式形成的日期。

【讨论】:

【参考方案2】:

您可以创建一个包含所有可能日期的表格

[DayOfMonth]

dd
--
 1
 2
 3
...
30
31

然后只需使用这样的查询为当月的每一天生成一行

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

将其用作 INSERT 查询将是

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())

【讨论】:

【参考方案3】:

请看下面的代码并阅读 cmets:

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

【讨论】:

【参考方案4】:

这是一个花哨的查询,它将返回一个月的日期:

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))

也就是说,我会编写一个循环,使用 VBA 将记录添加到记录集中,而不是您的慢速 SQL 调用。

【讨论】:

以上是关于使用 VBA 在 Access 表中插入当前月份的每个日期记录的主要内容,如果未能解决你的问题,请参考以下文章

Access vba:如何在两个相关表中执行插入?

使用 vba 将 xls/csv 文件插入到 access 2007 表中

VBA Access将数据集中的所有列插入访问表

Access 2010 VBA 不保存对字段的更改

Access-vba复制数据错误

大型记录集 (VBA) 的 MS Access 插入慢