How to insert values into the database table using VBA in MS access

后端 未结 3 741
自闭症患者
自闭症患者 2020-12-18 07:37

I\'ve started to use access recently. I am trying to insert a few rows into the database; however, I am stuck as it is throwing an error:

Too few par

相关标签:
3条回答
  • 2020-12-18 08:03
    1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
    2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

    in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

    0 讨论(0)
  • 2020-12-18 08:09

    since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.

    Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario

    Dim StrSQL As String
    Dim InDate As Date
    Dim DatDiff As Integer
    
    InDate = Me.FromDateTxt
    
    StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
    
    DoCmd.SetWarnings False
    DoCmd.RunSQL StrSQL
    DoCmd.SetWarnings True
    
    0 讨论(0)
  • 2020-12-18 08:10

    You can't run two SQL statements into one like you are doing.

    You can't "execute" a select query.

    db is an object and you haven't set it to anything: (e.g. set db = currentdb)

    In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.

    You might want to be a bit more specific about the date you are inserting:

    INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
    
    0 讨论(0)
提交回复
热议问题