0

I have some problem when inserting data to database. I am using mssql.

Private Sub EditMethodAdd_Click()

Dim rs As ADODB.Recordset
Dim introw
Dim strState As String
Dim strsql1 As String
Dim strsql2 As String
Dim all As String

Dim strConn As String
Dim conn As ADODB.Connection

MsgBox ("EditM1.Value:" & EditM1.value)


strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"

strsql1 = " INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
strsql2 = "   VALUES(EditM1.value, 'Piloting', EditM3.value, Null, Null, Null, Null, EditM2.value, EditM4.value, EditM5.value, EditM6.value, EditM7.value, EditM8.value, EditM9.value, EditM10.value, Null )"


all = strsql1 & strsql2

MsgBox ("ALL" & all)


Set conn = New ADODB.Connection
conn.Open strConn

Set rs = New ADODB.Recordset
rs.Open all, conn
MsgBox ("Insert Success")

EditMethodList.Requery

conn.Close
Set rs = Nothing
Set conn = Nothing

MsgBox "Data has been updated"
EditMethodList.Requery

End Sub

When I check the value for EditM1 by using MsgBox, it shows correct. But I got error message like this. enter image description here

Is there anyone who can solve this problem? Thank you in advance.

2 Answers 2

2

Delete the lines:

strsql1 = ...
strsql2 = ...

all = strsql1 & strsql2

and write this instead

all = "INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
all = all & "VALUES(" & EditM1.value & ", 'Piloting'," & EditM3.value & ", Null, Null, Null, Null," & EditM2.value & "," & EditM4.value & "," 
all = all & EditM5.value & "," & EditM6.value & "," & EditM7.value & "," & EditM8.value & "," & EditM9.value & "," & EditM10.value & ", Null )"

If you insert EditM1.value into doublequotes, as you did, VBA read it as a string and it does not refer to its value. You need to concatenate string and values with & to create your query.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't do this. Use a parameter query, here is an explanation and example: stackoverflow.com/a/46057683/3820271
2

You're putting the literal value "EditM1.value" into your SQL: you should instead be sending the Value of the control:

strsql2 = "   VALUES(" & EditM1.value & ", 'Piloting', " & _
                         EditM3.value & ", Null,..." 'etc

If any of the values being sent are not numeric then they should be wrapped in single quotes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.