I am not able to establish connection between SQL server and a VBA form. It's throwing the following error
Compiler Error:
User-defined type not defined
Here's the code with server details:
Private Sub CommandButton1_Click()
Dim cnn As ADODB.Connection
Dim cnn As ADODB.Command
Set cnn = New ADODB.Connection
Set cnn = New ADODB.Command
cnn.Open "Provider=sqloledb;" & _
"Data Source=<IP>;" & _
"Initial Catalog=<DB>;" & _
"User Id=<USER>;" & _
"Password=<PASS>"
MsgBox "connection successful"
cnn.Close
End Sub
You need to add a reference to Microsoft ActiveX Data Objects X.X Library where X.X is the ADO version.
You will then get an error on your second line because you are trying to re-declare your cnn variable.
Related
I'm writing a macro in Microsoft Excel that makes an update in a table of my local SQL Server database,.
My connection string:
sConnect = "Driver={SQL Server};Data Source=(localdb)\MSSQLLocalDB;Database=Scrape;"
I get this error:
Data source name not found and no default driver specific
How do I write the connection string?
Ok, this should be pretty simple. See the link below.
https://www.erpsoftwareblog.com/2017/01/microsoft-excel-connections-sql-databases/
Also, check this out.
https://www.connectionstrings.com/sql-server/
Finally, to update a SQL Server table with Excel/VBA code, do the following.
Sub UpdateMyTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim rngName As Range
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=MyDB;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
uSQL = "UPDATE MyTable SET Field = 1 WHERE Field = ' " & rngName & " ' "
'Debug.Print (uSQL)
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
Post back, with specific details, if you have issues with this code. Thanks.
I'm trying to create ODBC connection in order to be able to perform a simple sql query on one of the tables from my SQL DB.
Below is my code and I'm not sure what I'm doing wrong but I keep getting ActiveX can't create an object error and the following line is highlighted: Set con = CreateObject("ODBC.Connection").
Private Sub findBtn_Click()
Dim s
Dim con As Object 'OdbcConnection
Dim strCon
Dim rsSearch
Dim strSql
Dim mystring As String
Dim cmd 'As OdbcCommand
s = Me.findTxt
mystring = "Select * from CUSTOMER where CUSTOMER.FORENAME1 like '%" & s & "%';"
Set con = CreateObject("ODBC.Connection")
con.Open "ODBC;Driver={SQL Server};" & _
"Server=localhost;" & _
"Database=Customers23;" & _
"UID=admin;" & _
"PWD=admin;"
Set cmd = CreateObject("ODBC.Command")
cmd = mystring
Me.resTxt = "Connected!"
MsgBox ("Connected")
End Sub
Try to replace ODBC.Connection with ADODB.Connection.
Same with ODBC.Command
You can find an example here How do I setup an ADODB connection to SQL Server 2008 in Microsoft Access 2010?
Also see that link on how to use the Command object.
I'm a bit stuck for a while in a small project
to generate results from several
sql queries in several excel Sheets, I am trying to use SQL Server 2008 and it's the first time I code VBA
I tried this code (for a SQL single query) but I still have compilation problems
Sub New_Feuil1()
ThisWorkbook.Activate
'First clear the contents from the query
Worksheets("Feuil1").Select
Range("A2").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("A4", ActiveCell.Offset(-1, 3)).ClearContents
'Get reporting date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
'Format the value for use in the SQL query
ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd")
Worksheets("Feuil1").Select
Range("A1").Select
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim StrQuery1 As String
Dim ConnectionString As String
ConnectionString ="ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=187.125.254.231;" & _
"Database=database;" & _
"UID=sa; PWD=pwd"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
'Queries to be executed
StrQuery1 = StrQuery1 & "Select Id from Users"
rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly
rst.Close
Debug.Print "StrQuery1:"; StrQuery1
cnn.Close
ThisWorkbook.Sheets("Central Dashboard").Select
Sheets("Feuil1").Range("A2").CopyFromRecordset rst
End Sub
is there any other solution ?
it seems you are new to programming :).. before you use any variables please declare them this will help you to understand them quickly.
like:
Dim ReportingDate as Date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
Dim ReportingDateFor As String
ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd")
also check your connection string. try this connection string.
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
Apart from that, looking at your code you are connecting to server, opening recordset, closing recordset and finally closing the connection AND THEN trying to retrieve the results. logically this will never work :) :)
try this:
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim ConnectionString As String
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
cnn.Open ConnectionString
'Queries to be executed
Dim StrQuery1 As String
StrQuery1 = StrQuery1 & "Select Id from Users"
'Prepare SQL execution
cmd.Name = "SelectUsers"
cmd.ActiveConnection = conn
cmd.CommandText = StrQuery1
Set rst = cmd.Execute
If Not rst.EOF Then
With Sheets(1).Cells ' Enter your sheet name and range here
.ClearContents ' clears the entire sheet
.CopyFromRecordset rst ' copy the result
End With
Else
MsgBox "no records found.."
End If
'After work done close connection
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
I have a simple VBA code that needs to execute a SP from SQL Server with one parameter. I copied the code from a text book, making relevant adjustments, but I keep getting this error.
Here is the code:
Public Sub ExecuteStoredProcAsMethod()
Dim objConn As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim sConnect As String
'Create the conntection string.
sConnect = "Provider=SQLOLEDB;Data Source=MYSERVER; " & _
"Initial Catalog=DisaggregatedPatronage;Integrated Security=SSPI"
'Create the connection and Recordset objects.
Set objConn = New ADODB.Connection
Set rsDate = New ADODB.Recordset
'Open the connection and execute the SP.
objConn.Open sConnect
objConn.spSurveyDataTest "Bus", rsData
'Make sure we got records back
If Not rsData.EOF Then
'Dump the contens of the recodset on the worksheet
Sheet1.Range("A1").CopyFromRecordset rsDate
'Close the recordset
rsData.Close
'Fit the column wirdths to the data
Sheet1.UsedRange.EntireColumn.AutoFit
Else
MsgBox "Error: No records returned. ", vbCritical
End If
'Clean up our ADO objects.
If CBool(objConn.State And adStateOpen) Then objConn.Close
Set objConn = Nothing
Set rsData = Nothing
End Sub
You declare an rsData variable, but you initialize rsDate. Aren't you using the Option Explicit statement?
I'm using Excel 2010 VBA to retrieve data from MS Access 2010 with ODBC connection to SQL Server R2 Express, in my previous machine there is no issue (32bit platform) but when I got new machine it's always said "ODBC connection to (odbc name) failed -2147467259".
From Access 2010 to SQL there is no issue, but when I retrieve data from Excel always trigger this error.
I have check the permission for the user (DBO), all the app in the same machine, all the services are on, ODBC setting is correct. During the execution of the script all OK except when the line is opening the table.
Function RetrieveProjectList()
Dim strConn As String
Dim conn As New ADODB.Connection
Dim rec As New ADODB.Recordset
Dim intColCount As Integer
Dim strName As String
Dim strSQL As String
On Error GoTo Error_Trap
strName = ThisWorkbook.path & "\DBSource V0.1.accdb"
Set conn = New ADODB.Connection
strConn = "Provider=microsoft.ACE.oledb.12.0;"
strConn = strConn & "Data Source=" & strName & ";"
conn.Open ConnectionString:=strConn
Set rec = New ADODB.Recordset
strSQL = "SELECT qryProjectList.* " & _
"FROM qryProjectList ORDER BY tblArea.AreaName,tblProject.ProjectName;"
rec.Open strSQL, conn, adOpenDynamic, adLockOptimistic
'Retrieve data from Access
rec.MoveFirst
If rec.Fields.count <> 0 Then
After syntax "rec.open ...." the error pop up.
In other machince are OK.
Question:
Is this related to OS version 64bit? What did I miss out here?
Any advice will be highly appreciated.
Thanks, seageath