VBA is unable to create a connection to a remote SQL Database - vba

I've created an excel front end interface to connect with and manipulate an SQL database. I recently received a laptop, and would like to be able to manipulate the data from excel on said laptop. I established a connection using SQL Server Management Studios to the database.
I've tried to update my excel file; however, the VBA code can not connect to the SQL database. I've changed a few of the variables around and set Integrated Security too, but nothing has worked so far. The error message readouts can be seen here:
Here is the code related to the DB connection:
Dim cnSQL As ADODB.Connection
Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider = SQLOLEDB; Integrated Security = SSPI, Data Source = IP Address,Static TP Port; UID = username; PWD =pwd#; Initial Catalog = database"
The error message highlights the second line of code. I'm hoping to be able to connect to the DB from my laptop.

After struggling for a few days, I finally got this to work. There are two important steps you need to take to make excel work with a Remote SQL network. First here is the code used to connect:
Dim cnSQL As ADODB.Connection
Dim ServerName As String
Dim DatabaseName As String
Dim userID As String
Dim password As String
ServerName = "IP Addresss,Port"
DatabaseName = "DB Name"
userID = "username"
password = "pwd"
Set cnSQL = New ADODB.Connection
sqlCommand.ActiveConnection = cnSQL
After I changed the code to this, I got a new error: "optional feature not implemented." To fix this error, I changed the data type of all 'adDate' to 'adDBTimeStamp.' This works for some reason, I don't know why. It works.

Related

Is there a way to specify a proxy user id in a VBA Macro to connect to oracle?

I am currently trying to connect to an Oracle database from VBA. Below is the code I am running in VBA to try to establish the initial connection. Unfortunately, this code produces an “ORA-01017” error mentioning that my username/password is invalid. I have SQL Developer installed and when I try to login with the same credentials/info, I successfully connect. I also tried instead setting UID = userid in the VBA code below and the connection didn’t throw an error, but I can’t query any tables. The same thing happens if I try the same in SQL developer.
After doing some reading, it looks like the info in the brackets is my proxy user id and I need to somehow specify that separately from my UID, but I can’t figure out how I would go about that. Has anyone else had any experience with this or have any guidance? Let me know if there is any additional details I can provide.
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.recordset
Set con = New ADODB.Connection
Set rs = New ADODB.recordset
StrCon = "Driver={Microsoft ODBC for Oracle}; Uid=userid[database name];Pwd=UserPWD;" & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=HostName)(PORT=1521))" & _
"(CONNECT_DATA=(SERVICE_NAME=XXXX)));"
con.Open (StrCon)
End Sub
It doesn't look like its possible to connect to proxy user with ADODB .
One another alternative is to use alter session set current_schema = Proxy_user run this after you open the session.
The only trouble with this is that the grants should be there for the actual user, here proxy user just allows us to avoid using identifiers.

Accessing Oracle SQL Developer database from VBA

New to VBA and returning to SQL after 15 years. I'm am trying to use VBA to run SQL commands to download data into excel for further manipulation.
I have SQL Developer installed on my machine and I am able to access the database using the UI. I have figured out how to connect to the database and run a query within the SQL Developer interface, but honestly, I'm not an IT guy.
Any ideas how to do this? Even basic command line commands to connect to the database and run the query would be helpful.
I found this code on another site, but I'm having trouble getting my connection string to work. My macro errors out on the cnn.Open statement and says the Provider is not installed. I think it's because PROVIDER is set up for a different SQL Database type, but I can't seem to get the connection string to work.
I know my username and password, which I have successfully used to connect in the SQL Developer UI. I'm not sure what to put for remote IP address or database. Would that be the hostname and the SID in the connection properties dialog in SQL Developer? (The hostname looks more like a url without the http than an ip address. Not sure if hostname and ip address is an interchangeable term).
Sub Download_Reports()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=ORAOLEDB.ORACLE;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
I'm needing help with my connection string. Can anyone help me with this?
I'm connecting to a database via Oracle SQL Developer. I am able to connect within the UI by providing the following items:
Connection Name - got it.
myUsername - got it.
myPassword - got it.
Connection Type = Basic, Role = default
myHostname - got it.
myPort - got it.
mySID - got it.
However, I am unable to get my connection string to work in VBA. When I run the script I get
"Run-time Error '3076'. Provider cannot be found.
It may not be properly installed" on the line beginning with cnn.open.

SQL Management Studio 2012 with Excel vba connection string set up

I would like to set up a vba code that would connect to sql management studio 2012 a run the query, which I would specify in the vba code. I have read every similar question here on stack overflow but when I try to replicate them, I always get an error, ussualy that the login failed for user.
I think I am setting up the string connection wrong. Also, I would need the user authentication by Windows authentication.
I know the database name, server name and my user name.
This is the code I am using and which is giving me an error.
Sub ConnectionExample6()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
' Open a connection by referencing the ODBC driver.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=SERVER NAME;uid=USER ID;pwd=MyPassword;database=DATABASE NAME"
cnn.Open
' Create a Recordset by executing an SQL statement.
Set rs = cnn.Execute("Select top 100 * from "TABLE NAME" aac " & _
"where aac.EffectiveDate = '10/04/16'")
' Close the connection.
rs.Close
End Sub
Can someone walk me through the connection string and how to set it up step by step? Thank you.
Authentication
If you're connecting to SQL Server, you should prefer Windows Authentication if that's available: you create a Login at server level for a group of Active Directory users, and then you create a Windows-Authenticated User in your database using that login.
That way you are keeping passwords and usernames out of hard-coded strings, and let the network deal with authentication.
Assuming you don't want to be maintaining passwords in dozens of copies of macro-enabled workbooks across your network, you'll want to use Windows Authentication.
Integrated Security=SSPI; Persist Security Info=True;
Server
Connection strings are annoying - seems there's a different format/wording for every single different thing that's able to parse them!
Since you're using ADODB, you'll want to specify a Provider, a Data Source and, optionally, an Initial Catalog:
Provider=SQLOLEDB.1; Data Source=SQL Server instance name; Initial Catalog=Database name;
Who?
Each connection can be monitored on the server; when building your connection string you can optionally specify a Workstation ID to identify the machine the connection is for.
Workstation ID=computer name;
You can get the computer name by fetching the environment variable value, using Environ$:
Private Function GetWorkstationId() As String
GetWorkstationId = Environ$("ComputerName")
End Function
Given a SQL Server instance named SomeSqlServer, a database named SomeDatabase, and using Windows Authentication, the ADODB connection string would look like this:
Dim connString As String
connString = "Provider=SQLOLEDB.1; Data Source=SomeSqlServer; Initial Catalog=SomeDatabase; Integrated Security=SSPI; Persist Security Info=True;"
Given SQL Authentication (with a hard-coded user name and password) for SomeUser with SomePassword:
connString = "Provider=SQLOLEDB.1; Data Source=SomeSqlServer; Initial Catalog=SomeDatabase; UID=SomeUser; PWD=SomePassword;"
Commands
You don't want to be concatenating arbitrary user input into a WHERE clause; avoid executing an SQL string directly from the ADODB.Connection object.
Instead, create an ADODB.Command, and parameterize your query.
Dim sql As String
sql = "SELECT Foo, Bar FROM dbo.FooBars WHERE Foo = ? AND DateInserted > ?"
Here we have 2 parameters.
First we create the command:
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = sql
Then its parameters, assuming we have their respective values in param1Value and param2Value local variables:
Dim param1 As ADODB.Parameter ' a string parameter
Set param1 = New ADODB.Parameter
param1.Type = adVarWChar
param1.Direction = adParamInput
param1.Size = Len(param1Value)
param1.Value = param1Value
cmd.Parameters.Append param1
Dim param2 As ADODB.Parameter ' a date parameter
Set param2 = New ADODB.Parameter
param2.Type = adDate
param2.Direction = adParamInput
param2.Value = param2Value
cmd.Parameters.Append param2
Then we retrieve the recordset by executing the command:
Dim results As ADODB.Recordset
Set results = cmd.Execute
Of course this looks very verbose, but it can easily be refactored into functions dedicated to creating a parameter given a value of a certain type.
As a result, you avoid this situation, because you're no longer executing arbitrary user input concatenated into a query:

OLEDB Connection from Excel to Oracle Issue

Everyone,
A VBA problem has been killing me the past two days. I have a Macro Based Model in Excel that has data sets bought into the spreadsheets from Oracle via OLEDB. To illustrate the problem simply I have created two functions within the Model. One using ODBC("odbc") and another using OLEDB("OraOLEDB"). The code was working completely fine last week and it has not been changed.
Now, however I get an error message that states "Run-Time Error '424': Object Required when I execute the line "conn.Open strCon" in sub "OraOLEDB".A connection can't be established with the database! So when I am trying to establish a connection to the database with that line of code, it fails. What is interesting is that via ODBC, a connection can be established. The line "conn.Open strCon" in sub "odbc" executes successfully and I am able to establish a connection to the database.
I did not change anything in the Excel Model but I did have a bunch of windows updates recently. I don't know if that corrupted anything. I think it may have. The reason why I don't want to use the ODBC connection is that it is significantly slower. I get run times 10x faster using OLEDB. Please let me know if you can help.
Sub odbc()
Dim conn As Object
Dim strCon As String
strCon = "Driver={Microsoft ODBC for Oracle};
CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=xxx)));
uid=xxx;pwd=xxx;"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
End Sub
Sub OraOLEDB()
Dim conn As Object
Dim strCon As String
strCon = "Provider=OraOLEDB.Oracle;
Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)
(HOST = xxx)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = xxx)));
User Id=xxx;Password=xxx"
Set conn = CreateObject("ADODB.Connection")
conn.Open strCon
I see the host for the OLEDB connection is modn-ast-fdb1. ... while for the ODBC connection you have modn-ast-tdb1. ... Shouldn't the host be the same?
This means Set conn = CreateObject("ADODB.Connection") returns nothing. Check ADODB.dll registration. Alternatively you may use
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
and you'll see if ADODB is available at the moment you edit the script not waiting for runtime errors.

Creating a workspace session using SAS IOM & VBA

I am trying to connect to a workspace server using Excel VBA. Using the information on this page, I have produced the following:
Dim obSAS As SAS.Workspace
Dim obWorkspaceManager As New SASWorkspaceManager.WorkspaceManager
Private Sub Form_Load()
Dim obConnection As New ADODB.Connection
Dim obRecordSet As New ADODB.Recordset
Dim obServerDef As New SASWorkspaceManager.ServerDef
Dim xmlString As String
obServerDef.Port = 28561
obServerDef.Protocol = ProtocolBridge
obServerDef.MachineDNSName = "blah.server.com"
Set obSAS = obWorkspaceManager.Workspaces.CreateWorkspaceByServer( "Ref", _
VisibilityProcess, obServerDef, "me#saspw","MyPass", xmlStr)
end sub
My first response was this:
<xml id="combridgeOutput"><connectionAttempts><connectionAttempt>
<sasserver></sasserver>
<sasmachinednsname>blah.server.com</sasmachinednsname>
<sasport>28561</sasport>
<saslogin>me#saspw</saslogin>
<status>0x80041001</status>
<description><Exceptions><Exception>
<SASMessage severity="Error">
The client has connected to a SAS (9.2) Metadata Server (v1.0) when
it intended to connect to a SAS Workspace Server.
</SASMessage>
</Exception></Exceptions></description>
</connectionAttempt></connectionAttempts></xml>
So I updated the port number to point at the workspace server, and now I get this:
<same XML tags as above >
<SASMessage severity="Error">
Client me#saspw does not have permission to use server
SASMeta - Workspace Server (A5DPDN69.AV000069).
</SASMessage>
Would rather not set special permissions for this exercise. How else can one connect VBA to a SAS workspace server session?
Doh! I was using the wrong machine name. For reference, here is the process for getting the correct machine name!
Log into SMC
Expand Server Manager
Expand SASApp
Expand SASApp - Logical Workspace Server
There you will see the correct machine, and will also show the port details..