vba ActiveX can't create odbc.connection object - sql-server

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.

Related

Connect to SQL Server local database

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.

Using both Excel and Microsoft SQL Server Connection Strings

My task is to add new records from an excel table to a Microsoft SQL Server table, and to do this, I was planning on using ADODB objects; however, my SQL statement is not executing, and I think it has something to do with my connection strings.
In my code, I wrote down the SQL statement that I plan on using in the end, but when I tried:
sql = "SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01; _
Initial Catalog=HPW DataIntegrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data"
(a simple select statement) it didn't even work.
Sub update1()
Dim cn, rs As Object, path As String, name As String, sql As String, file As String
path = "T:\Marketing\Data Analytics\Hubspot data for SQL"
name = "Hubspot_Data"
file = path & "\" & name & ".xlsx"
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & file & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;Readonly=false;IMEX=0"";"
.Open
End With
sql = "INSERT INTO [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data " & _
"SELECT * FROM (SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data" & _
"EXCEPT SELECT * FROM [hubspot-crm-exports-sql-data-20$])"
Set rs = cn.Execute(sql)
End Sub
Just a side note: the table is named the same thing as the database
For this code, I have gotten three different errors:
The Microsoft Access database engine could not fin the object 'Area' Make
sure the object exists and that you spell its name and the path name
correctly. (And I did not misspell Hubspot_Data)
External table is not in the expected format.
The Microsoft Acess database engine cannot open or write to the file
(My File Path)'\My Documents\Provider=SQLOLEDB.XLSX'. It is already opened
exclusively by another use, or you need permission to view and write its
data.
Clearly the computer is going to the wrong place to retrieve the table it needs, and I have no idea where I went wrong. Thanks for the help.
First of all you need 2 connections - one for SQLSvr and one for Excel.
Then query your source (Excel) and do a separate insert into SQLSvr. You are not going to be able to mix these into one query.
Sub SelectInsert()
Dim cn As Object, rs As Object, sql As String
Dim conSQL As Object, sInsertSQL As String
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Set conSQL = CreateObject("ADODB.Connection")
With cn
.Provider = "SQLOLEDB"
.ConnectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
.Open
End With
'---Run the SQL SELECT Query---
sql = "SELECT * FROM [Sheet1$]"
Set rs = cn.Execute(sql)
Do 'the insert. Each rs(n) represents an Excel column.
sInsertSQL = "INSERT INTO table VALUES(" & rs(0) & ";" & rs(1) & ";" & rs(2) & ")"
conSQL.Execute sInsertSQL
rs.MoveNext
Loop Until rs.EOF
'---Clean up---
rs.Close
cn.Close
conSQL.Close
Set cn = Nothing
Set conSQL = Nothing
Set rs = Nothing
End Sub
get properties of your database from "SQL Server Object explorer" and copy the exact same connection string. then copy it to the "appsettings.json" file of your project. It looks like this :
"connectionStrings": {
"ApiDbConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ApiDB;Trusted_Connection=True;"
}
then you need to create an object in your connection string and open a connection to the database using that object, then write your SQL query to the database

How do run a stored procedure from SQL in VBA and then paste the data into Excel?

So I am quite new to VBA but I need to write a VBA macro which runs the stored procedure in Microsoft SQL server and then paste this data into the excel worksheet.
So far this is the code that I have, but I am not sure how to proceed? Is there sample code or a template for this particular procedure?
Sub Connection() ' create the connection
loginstatus = True
login.Show
Password = login.password_input
user = login.UserName
Dim con As ADODB.Connection
Dim stored_procedure As String
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
'provide and create connection string
Dim connectionString As String
Dim location As String 'the server
location = "MyLocation"
connectionString = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ukmc; User ID=" & user & "; Password=" & Password & ";"
'handle when it is not possible to log in
On Error GoTo ConnectionError
con.Open connectionString
loginstatus = False
Exit Sub
'errorhandl0
ConnectionError:
MsgBox "Not possible to log in. Have you entered the correct password?"
'recordset - the data extracted
Set ADODBCmd = New ADODB.Command
End Sub
So i think I have created the connection, but how do I tell it which stored procedure to run and then how do i paste the data into a worksheet in my excel document?
From the link
myConnection.Open
Set myCommand.ActiveConnection = myConnection
Set myRecordSet.ActiveConnection = myConnection
myCommand.CommandText = strSQL
myCommand.CommandType = adCmdText
myCommand.Execute
myRecordSet.Open myCommand
'Paste to spreadsheet
ThisWorkbook.Worksheets("Report").Range("a2").CopyFromRecordset
myRecordSet

Excel VBA ODBC connection failed

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

Connectivity between SQL server and VBA

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.

Resources