espenskeie
Well-known Member
- Joined
- Mar 30, 2009
- Messages
- 636
- Office Version
- 2016
- Platform
- Windows
Hi
I try to add data to an SQL DB directly from Excel, but I get an run-time error saying that Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
Could it be that the SQL is blocked for editing from the "outside"?
Here's my code:
This is where the VBA stops:
Kind regards
Espen
I try to add data to an SQL DB directly from Excel, but I get an run-time error saying that Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
Could it be that the SQL is blocked for editing from the "outside"?
Here's my code:
Code:
Sub SQLIM()
' Send data to SQL Server
' This code loads data from an Excel Worksheet to an SQL Server Table
' Data should start in column A and should be in the same order as the server table
' Autonumber fields should NOT be included'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
Dim Cn As ADODB.Connection
Dim ServerName As String
Dim DatabaseName As String
Dim TableName As String
Dim UserID As String
Dim Password As String
Dim rs As ADODB.Recordset
Dim RowCounter As Long
Dim ColCounter As Integer
Dim NoOfFields As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim shtSheetToWork As Worksheet
Set shtSheetToWork = ActiveWorkbook.Worksheets("Sectors")
Set rs = New ADODB.Recordset
ServerName = "localhost\SQL2008E" ' Enter your server name here
DatabaseName = "pairTradeFinder" ' Enter your database name here
TableName = "portfolios" ' Enter your Table name here
UserID = "" ' Enter your user ID here
' (Leave ID and Password blank if using windows Authentification")
Password = "" ' Enter your password here
NoOfFields = 19 ' Enter number of fields to update (eg. columns in your worksheet)
StartRow = 2 ' Enter row in sheet to start reading records
EndRow = shtSheetToWork.Cells(Rows.Count, 1).End(xlUp).Row ' Enter row of last record in sheet
' CHANGES
' Dim shtSheetToWork As Worksheet
' Set shtSheetToWork = ActiveWorkbook.Worksheets("Sheet1")
'********
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & _
";Uid=" & UserID & ";Pwd=" & Password & ";"
rs.Open TableName, Cn, adOpenKeyset, adLockOptimistic
For RowCounter = StartRow To EndRow
rs.AddNew
For ColCounter = 1 To NoOfFields
rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
Next ColCounter
Next RowCounter
rs.UpdateBatch
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
This is where the VBA stops:
Code:
rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
Kind regards
Espen
Last edited: