VBA:在表格中插入升序日期

时间:2016-09-06 09:27:56

标签: sql forms vba ms-access

我试图通过代码简化用户的输入。解释这个过程很难,所以我告诉你我的意思。

用户只需输入以下值:

活动event1 来自:01.01.2017 01.04.2017 费用5000

表中的结果:

event1   01.01.2017   5000
event1   01.02.2017   5000
event1   01.03.2017   5000
event1   01.04.2017   5000

我尝试使用此代码:

Private Sub Save_Click()

Dim strSQL As String
Dim Period As Date

    For Period = "' & Me!FromDate & '" To "' & Me!ToDate & '"

    strSQL = "INSERT INTO tblEvents (EventName, Date, Costs) VALUES ('" & Me!EventName& "' , '" & Date & "', '" & Me!Costs& "')"
    CurrentDb.Execute strSQL

    Next Date

End Sub

1 个答案:

答案 0 :(得分:1)

您应该使用以下日期计算功能:

  1. DateDiff()计算两个日期之间的月数
  2. DateAdd()通过将日期添加到另一个日期来创建日期
  3. 编辑:为数据输入添加infor

    在表单中添加2个文本框,将其命名为TextDtFromTextDtTo,并为其提供 shortdate 格式,以便您可以看到日历日期很容易。

    使用此点击事件添加一个按钮:

    Private Sub TheButton_Click()
    
    
        Dim strSQL As String
        Dim dtFrom As Date
        Dim dtTo As Date
        Dim dtCurrent As Date
        Dim intMonths As Integer
        Dim i As Integer
    
        'dtFrom = DateSerial(2017, 1, 1)
        'dtTo = DateSerial(2017, 4, 1)
    
        dtFrom = TextDtFrom.Value
        dtTo = TextDtTo.Value
    
        ' Calculate the number of months between the 2 dates
        intMonths = DateDiff("m", dtFrom, dtTo)
    
        ' Looping on the number of months
        For i = 0 To intMonths
    
            ' Computing Datefrom + month
            dtCurrent = DateAdd("m", i, dtFrom)
    
            strSQL = "INSERT INTO tblEvents (EventName, Date, Costs) VALUES ('" & Me!EventName & "' , '" & Format(dtCurrent, "DD.MM.YYYY") & "', '" & Me!Costs & "')"
    
            CurrentDb.Execute strSQL
    
        Next i
    
    
    End Sub
    
相关问题