2016-05-29 39 views
0

我是VBA編程的新手。我設計了一個有按鈕的表單。點擊這個按鈕後,我想在我的表格中插入有一個日期列的記錄。虛擬記錄的數量應該等於當月的天數。如果月是2016年5月,那麼記錄將插入日期1/5/2016, 2/5/2016 ....... 31/5/2016那樣。使用VBA在Access表中插入當前月份的每個日期記錄

在此先感謝。

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

使用'for ... next'循環。 –

回答

2

下面的表達式將會給你一個整數,日的當月數:

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

這是下一個月的0天,這是目前的最後一天月。如果從十二月移到一月,這個表達方式仍然有效。

將其存儲在一個變量中,比如說lastDay然後使用循環For x = 1 To lastDay來執行插入。

在循環中,這種表達

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

會給你日期2016年1月5日,2016年2月5日,..,31/5/2016。

插入時,還應該用日期分隔符#圍繞日期。同日yyyy-mm-dd(這樣個月內將不會被解釋爲天)的ISO格式結合本:

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

其中dtValue是你使用以前DateSerial表達剛剛成立的日期。

0

請參見下面的代碼和閱讀評論:

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 
0

這裏是一個奇特的查詢將返回一個月的日期:

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的慢速調用。

1

您可以創建包含每一個可能的天數

[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()) 
相關問題