I'm trying to upload some data into a SQL database from a spreadsheet. I'm Using the code from here as a base, had to make a few mods in order to get it to work.
Sub newtest()
Dim conn As ADODB.Connection
Dim cmd As New ADODB.Command
Dim cs As String
Dim C1, C2, C3, C4 As String
Dim RowNo As Long
Dim wbk As Workbook
Dim strFile As Variant
Dim shtname As String
ChDir "xxxxxx"
strFile = Application.GetOpenFilename
If strFile = False Then
Exit Sub
Else: End If
Application.ScreenUpdating = False
Set conn = New ADODB.Connection
cs = "Provider=SQLOLEDB;Data Source=xxxxx;Initial Catalog=xxxx;User ID=xxx; Password=xxxxxx; "
conn.ConnectionString = cs
conn.Open
' *** Open workbooks first ***
Set wbk = Workbooks.Open(strFile)
shtname = ActiveWorkbook.Worksheets(1).Name
lastrow = wbk.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row + 1
With Sheets(shtname)
cmd.ActiveConnection = conn
cmd.CommandText = "insert into EcommerceXRefMapping_C_Copy values (@EquivalentPartNumber_C, @Manufacturer_C, @CatamacPartNumber_C, @Notes_C)"
cmd.NamedParameters = True
'Skip the header row
RowNo = 2
'Loop until empty cell in Col 1
Do Until .Cells(RowNo, 1) = ""
i = i + 1
C1 = .Cells(RowNo, 1)
C2 = .Cells(RowNo, 2)
C3 = .Cells(RowNo, 3)
C4 = .Cells(RowNo, 4)
'Generate and execute sql statement to import the excel rows to SQL Server table
cmd.Parameters.Append cmd.CreateParameter("@EquivalentPartNumber_C", adVarChar, adParamInput, 256, C1)
cmd.Parameters.Append cmd.CreateParameter("@Manufacturer_C", adVarChar, adParamInput, 256, C2)
cmd.Parameters.Append cmd.CreateParameter("@CatamacPartNumber_C", adVarChar, adParamInput, 256, C3)
cmd.Parameters.Append cmd.CreateParameter("@Notes_C", adVarChar, adParamInput, 256, C4)
cmd.Execute
RowNo = RowNo + 1
Loop
End With
wbk.Close
Application.ScreenUpdating = True
End Sub
I'm getting an error when trying to execute
cmd.execute
The error message is
Run-time error'-2147217800 (80040e14)':
Must declare the scalar variable "@EquivalentPartNumber_C".
Any ideas how to fix? I thought that the declaring of the variables was done with the "@" character? Sorry, I'm quite new to VBA so please bear with me.
Thanks!