Thursday, April 12, 2012

Excel to SQL-Server Insert in vba apostrophe in sql

Excel to SQL-Server Insert in vba.ado.net, connectionstring & handling apostrophe 

Private Sub CommandButton1_Click()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long
 
sConnString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=visliDB;Data Source=USER-PC\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=USER-PC;Use Encryption for Data=False;Tag with column collation when possible=False"
Set adoCN = CreateObject("ADODB.Connection")
adoCN.Open sConnString
For lRow = 2 To 11
   'replace
   Dim MyString As String
   MyString = Replace(Sheet1.Cells(lRow, 3), "'", "''")
   MyString = Replace(MyString, """", """")
   FixMyString = MyString
   
    sSQL = "INSERT INTO YRTAB (FIELD1, FIELD2, FIELD3) " & _
            " VALUES (" & _
            "'" & Sheet1.Cells(lRow, 1) & "', " & _
            "'" & Sheet1.Cells(lRow, 2) & "', " & _
            "'" & FixMyString & "')"
    adoCN.Execute sSQL
Next lRow
adoCN.Close
Set adoCN = Nothing
End Sub

No comments: