Link to home
Start Free TrialLog in
Avatar of Rob M.
Rob M.Flag for United States of America

asked on

From Excel pass a value to a SQL Server stored procedure with a single quote and transform to two single quotes: Test's to Test''s

I have an excel spreadsheet that inserts a security code and security description into a table. Clicking a Command Button executes a SQL Server stored procedure for the insert. The issue I am having is that some securities contain a singe quote (Test's) and error when passed to the stored procedure. I want to pass two single quotes (Test''s) to the stored procedure even though the security is entered as a single quote in the cell.

Example: Test’s will give me an error when passed to the stored procedure. Test’’s does not error when passed to the stored procedure.

I have attached a very basic security loader spreadsheet, stored procedure and table creation.

SecurityLoader.xlsm

Table-and-Stored-Procedure-Creation.sql

Code I wish to modify for the single quote to double quote transformation:

Private Sub CommandButton1_Click()
    Dim conn As New ADODB.Connection
    Dim iRowNo As Integer
    Dim sSecurityCode, sSecurityDesc As String

      With Sheets("Securities")
           
        'Open a connection to SQL Server
        conn.Open "Provider=SQLOLEDB;Data Source=YourSQLServer;Initial Catalog=TestDb;Integrated Security=SSPI;I"

        'Skip the header row
        iRowNo = 2
   
        'Loop until empty cell in CustomerId
        Do Until .Cells(iRowNo, 1) = ""
            sSecurityCode = .Cells(iRowNo, 1)
            sSecurityDesc = .Cells(iRowNo, 2)

             conn.Execute "testdb.dbo.uspSecurities '" & sSecurityCode & "', '" & sSecurityDesc & "'"
            iRowNo = iRowNo + 1
        Loop
       
        MsgBox "Securities imported."
       
        conn.Close
        Set conn = Nothing

    End With

End Sub
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rob M.

ASKER

Norie. Worked perfectly. Thank you very much.