Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Other SQL Server 2008 Topics
 Accessing SQL Server From VBA

Author  Topic 

martes
Starting Member

13 Posts

Posted - 2011-03-14 : 15:18:26
I wonder if anyone can help me with this problem in accessing SQL Server 2008 R2 from VBA.

The code I am using is shown below.

I get an error that the SQL Server does not exist, or access is denied. The server is the same as I use to access via SSMS, so I guess that is okay. Authentication is via Windows Authentication, is this the problem.

It fails on the line mpConnection.Open.

I have done this before, a long time ago, so I know it can work.

Any insights appreciated.

Bob

Private Enum ADOConstants
adUseServer = 2
adCmdText = 1
adModeWrite = 2
adPromptAlways = 1
End Enum

Private Function ExportToSQLServer()
Dim mpConnection As Object
Dim mpCommand As Object
Dim mpSQL As String
Dim i As Long

Const mpConn As String = "Provider=SQLOLEDB;" & _
"Data Source=MyServer;" & _
"Initial Catalog=MyDatabase;" & _
"User Id=MyUser;" & _
"Password=MyPassword"

mpSQL = "SELECT * FROM 'My Table'"

Set mpConnection = CreateObject("ADODB.Connection")
With mpConnection

.ConnectionString = mpConn
.CursorLocation = adUseServer
.Mode = adModeWrite
End With

Set mpCommand = CreateObject("ADODB.Command")
With mpCommand

mpConnection.Open
.ActiveConnection = mpConnection
.CommandType = adCmdTextommandText = mpSQL
.Execute

'do stuff

.ActiveConnection.Close
End With

Set mpCommand = Nothing
Set mpConnection = Nothing

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Function

martes
Starting Member

13 Posts

Posted - 2011-03-15 : 14:51:19
I've found the problem with this.

The connection Open was embedded in the command With clause, using the connection object variable. This failed because that object hadn't been full created. Moving the Open up to the connection With clause resolved it.

Just a dumb logic error.
Go to Top of Page
   

- Advertisement -