shravya shravya - 1 year ago 238
SQL Question

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

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 which says Too parameters.
I have a table test with only one column in it named start_date I want to insert all the dates between two dates for example if I consider 1/7/2014 to 3/7/2014 I need dates as 1/7/2014,2/7/2014,3/7/2014 in my table, but I have problem inserting the code I used is as follows

Private Sub createRec_Click()
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
Dim db As database
'here I have used a code to find out the difference between two dates that i've not written
For i = 1 To DatDiff
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
StrSQL = StrSQL & "SELECT 'Test'"
db.Execute StrSQL
next i
End Sub

My code throws an error in the line Db.Execuite StrSQL
as too few parameters.
Hope somebody could help me with this issue.
Thanks In advance

Answer Source

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.SetWarnings True
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download