将日期输入从TextBox中的MS Access VBA中的查询中

时间:2017-06-04 11:25:52

标签: sql database vba ms-access access-vba

我正在尝试从表单中获取输入,并且我想在单击按钮时执行插入查询(追加查询)。

这是我的代码:

Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")


End Sub

一切正常,但添加记录后,日期值的列保持空白。

文本框格式设置为"常规日期",并使用日期选择器选择日期。

3 个答案:

答案 0 :(得分:1)

您的Form_Form1!tbDate值是字符串,因此请转换为日期。 当你的字段类型是datetime时,然后将#date1#作为Expr5“。

Private Sub Command103_Click()
        Dim enrollment As String
        enrollment = Form_Form1!tbEnrollment

        Dim amount As String
        amount = Form_Form1!tbAmount

        Dim year As Integer
        year = Form_Form1!tbYear

        Dim date1 As Date
        date1 = DateValue(Form_Form1!tbDate)

        Dim month As Integer
        month = Form_Form1!cbMonth

        Dim sqlqry As String

        Dim db As DAO.Database
        Set db = CurrentDb
        sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, #" & date1 & "# AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
        MsgBox (sqlqry)

        db.Execute sqlqry

        MsgBox ("done")


    End Sub

答案 1 :(得分:0)

您将所有值连接起来,就像它们是文本一样,但它们不是。

您可以使用此函数将值正确转换为字符串表达式:

' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
'   SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
'   SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
'   SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
'   SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
    ByVal Value As Variant) _
    As String

    Const vbLongLong    As Integer = 20
    Const SqlNull       As String = " Null"

    Dim Sql             As String
    Dim LongLong        As Integer

    #If Win32 Then
        LongLong = vbLongLong
    #End If
    #If Win64 Then
        LongLong = VBA.vbLongLong
    #End If

    Select Case VarType(Value)
        Case vbEmpty            '    0  Empty (uninitialized).
            Sql = SqlNull
        Case vbNull             '    1  Null (no valid data).
            Sql = SqlNull
        Case vbInteger          '    2  Integer.
            Sql = Str(Value)
        Case vbLong             '    3  Long integer.
            Sql = Str(Value)
        Case vbSingle           '    4  Single-precision floating-point number.
            Sql = Str(Value)
        Case vbDouble           '    5  Double-precision floating-point number.
            Sql = Str(Value)
        Case vbCurrency         '    6  Currency.
            Sql = Str(Value)
        Case vbDate             '    7  Date.
            Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
        Case vbString           '    8  String.
            Sql = Replace(Trim(Value), "'", "''")
            If Sql = "" Then
                Sql = SqlNull
            Else
                Sql = " '" & Sql & "'"
            End If
        Case vbObject           '    9  Object.
            Sql = SqlNull
        Case vbError            '   10  Error.
            Sql = SqlNull
        Case vbBoolean          '   11  Boolean.
            Sql = Str(Abs(Value))
        Case vbVariant          '   12  Variant (used only with arrays of variants).
            Sql = SqlNull
        Case vbDataObject       '   13  A data access object.
            Sql = SqlNull
        Case vbDecimal          '   14  Decimal.
            Sql = Str(Value)
        Case vbByte             '   17  Byte.
            Sql = Str(Value)
        Case LongLong           '   20  LongLong integer (Valid on 64-bit platforms only).
            Sql = Str(Value)
        Case vbUserDefinedType  '   36  Variants that contain user-defined types.
            Sql = SqlNull
        Case vbArray            ' 8192  Array.
            Sql = SqlNull
        Case Else               '       Should not happen.
            Sql = SqlNull
    End Select

    CSql = Sql & " "

End Function

答案 2 :(得分:0)

a)您需要使用#包装日期值。

b)YearMonth是保留关键字,请考虑更改它们。

c)金额应该是数字字段(?),但是将它们包装在'引号中,你把它们作为字符串传递。

d)使用带参数的查询。

查询SQL:

PARAMETERS 
    [prmEnrollmentNo] Long, 
    [prmFeeMonth] Long, 
    [prmFeeYear] Long, 
    [prmAmount] IEEESingle, 
    [prmDateOfPayment] DateTime;

INSERT INTO StudentFeeMonthly (StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo)
SELECT (SELECT DISTINCT StudentDetails.StudentID 
        FROM StudentDetails 
        WHERE StudentDetails.EnrollmentNo=[prmEnrollmentNo]), 
        [prmFeeMonth], 
        [prmFeeYear], 
        [prmAmount], 
        [prmDateOfPayment], 
        "Hello";

在代码中调用查询:

With CurrentDb().QueryDefs("YourInsertQueryName")
    .Parameters("[prmEnrollmentNo]").Value = enrollment
    .Parameters("[prmFeeMonth]").Value = Month 'change it
    .Parameters("[prmFeeYear]").Value = Year   'change it
    .Parameters("[prmAmount]").Value = amount
    .Parameters("[prmDateOfPayment]").Value = date1
    .Execute dbFailOnError
End With

注意:

我假设字段以“...否”结尾,例如 EnrollmentNo 是数字。