Excel Azure SQL Server execute command error - sql

I can't seem to work out why my executing code is not working. Any help is appreciated. Datatypes are either int, nvarchar, or one column being datetime2. I have copied the connection string from my Azure portal
Cheers
Sub Upload_Data()
Dim oConn As ADODB.Connection
Dim sSQL As String
Set oConn = New ADODB.Connection
SQLSERVER_CONN_STRING = "Provider=SQLNCLI11;Server=tcp:myserver,1433;Initial Catalog=nzab_server;Persist Security Info=False;User ID=userid;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;"
oConn.Open SQLSERVER_CONN_STRING
oConn.Execute "INSERT INTO dbo.Database([Group],[Client],[Enterprise],[Shed],[Version_Name],[Version_Number],[Fiscal_Year],[Period],[Month],[Version_Period],[Client_Account_L1],[Client_Account_L2],[Client_Account_L3],[NZAB_Account_Group],[NZAB_Account],[Time],[Username],[Value],[Corrected_Value]) VALUES(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,16000101,1,1,1)"
MsgBox ("Data Uploaded")
If Not oConn Is Nothing Then
If oConn.State = 1 Then oConn.Close
End If
End Sub

Related

connecting to sql server via vba/odbc

I'm not sure what is wrong with my code here, it is not throwing any errors and is compiling successfully. However, the recordset is not grabbing any data. Nothing is being pasted into the sheet. The query itself runs fine from command line/sqlserver. Do I need to add a dsn somewhere in the connection string?
Sub queryTest()
Dim connection As New ADODB.connection
Dim recordset As ADODB.recordset
Dim strSQL As New ADODB.Command
connection.Open "DRIVER={SQL Server};SERVER=xxx;" & _
"trusted_connection=yes;DATABASE=xxxx"
strSQL.ActiveConnection = connection
strSQL.CommandText = "SELECT TOP (50) [CalendarSK] ,[CalendarMonthSK] ,[CalendarDate] FROM [xxxx].[dbo].[tblCalendar]"
strSQL.CommandType = adCmdText
Set recordset = strSQL.Execute
Sheets("Sheet1").Range("a1").CopyFromRecordset recordset
recordset.Close
connection.Close
End Sub

Connection String for MS Access Database incorrect

I am trying to extrapolate data from an MS Access 2007/2010 Database.
I have the following code in VBA but the connection string is incorrect. I have added the relevant REFERENCES libraries
Private Sub btnGetMsAccessData_Click()
Dim sConn As String
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sSQL As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"
Set oConn = New ADODB.Connection ' Open a connection.
oConn.Open
sSQL = "SELECT * FROM Tbl_Start_Leaver" ' Make a query over the connection.
Set oRs = New ADODB.Recordset
oRs.Open sSQL, , adOpenStatic, adLockBatchOptimistic, adCmdText
MsgBox oRs.RecordCount
oConn.Close ' Close the connection.
Set oConn = Nothing
End Sub
It fails saying Unknown Application error on the oConn.Open line.
I have tried to link a Workbook to one of the tables and this works fine.
I then looked at the "Connection" and copied it into my code but still no joy.
Keeps saying :
Automation Error
Unexpected Error
Any ideas would be appreciated.
Thanks in advance.
While the connection string was incorrect, there were other issues as well. Such as, not assigning the connection String to the ADODB Connection object as well as others. Here is the updated code that I hope will get you operational
Private Sub btnGetMsAccessData_Click()
'Ensure you add a reference to Microsoft ADO Objects
Dim oConn As New ADODB.Connection
Dim oRs As New ADODB.Recordset
Dim sSQL As String: sSQL = "SELECT * FROM Tbl_Start_Leaver"
'Corrected Connection String from Thomas Inzina
Dim sConn As String: sConn = "Provider=Microsoft.ACE.OLEDB.12.0;UID=Admin;Data Source=" & _
"\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"
With oConn
.ConnectionString = sConn ' You need to assign the connection string to the ADODB.Connection Object
.Open
End With
'Make sure the connection isn't open before opening the recordset
'You also need to specify which connection you want to use as the second parameter (this was missed)
If oRs.State <> adStateOpen Then oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText
'Close Connection and RS
If oConn.State = adStateOpen Then oConn.Close
If oRs.State = adStateOpen Then oRs.Close
'Clean Up
Set oRs = Nothing
Set oConn = Nothing
End Sub

VBA run time error 3704 with recordset in Excel

Good day.
When this piece of code hits "While Not objMyRecordset.EOF", I receive run time error 3704. In addition to this, when I hover over the "objMyRecordset" portion of "strPSTPath = CStr(objMyRecordset("PSTPath"))", i see error beginning "objMyRecordSet(PS... =
My SQL query works fine when used in SQL server management studio. The error occurs instantaneously upon hitting the line in question. I have stepped through the code line by line. Any thoughts would be appreciated. Thank you.
Sub Button3_Click()
'******
'Variables
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open connection
objMyConn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=XXXX;Data Source=XXXX"
objMyConn.Open
'Set and execute SQL command
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "<Valid SQL Command removed for public code display>"
objMyCmd.CommandType = adCmdText
'Open recordset
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open objMyCmd
While Not objMyRecordset.EOF
strPSTPath = CStr(objMyRecordset("PSTPath"))
MsgBox strPSTPath
objMyRecordset.MoveNext
Wend
End Sub
Try this:
Sub Button3_Click()
Dim SQL As String, strPSTPath As String
Dim objMyConn, objMyRecordset
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
objMyConn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;Initial Catalog=XXXX;Data Source=XXXX"
SQL = "<Valid SQL Command removed for public code display>"
objMyRecordset.Open SQL, objMyConn
While Not objMyRecordset.EOF
strPSTPath = CStr(objMyRecordset("PSTPath"))
MsgBox strPSTPath
objMyRecordset.MoveNext
Wend
End Sub
It has been a while since I used VBA and ADODB, but instead of opening the recordset object, I believe you need to execute the command object:
set objMyRecordset = objMyCmd.Execute
Have a look at this link.
Tracked down the problem. The connection string was incorrect for the version of SQL on this particular server. Changed the connection string to:
Driver={SQL Server Native Client 11.0};Server=XXXX;Database=XXXX;Trusted_Connection=yes;
Now everything works.

VBA New Database Connection

How to change the code below to prevent what you see in the screenshot.
I am running a macro with the following code
Dim conn As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim thisSql As String
Set conn = New ADODB.Connection
Dim sConn As String
sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=xyz;Database=xyz;UID=xyz;PWD=xyz"
conn.Open sConn
' this is creating multiple connections.
Set rec1 = New ADODB.Recordset
rec1.Open thisSql, conn
which runs a SQL Server query (which is around 20 lines long and contains 4 joins). Everything is fine except for the fact that after a couple times of running it my DB admin says that my query is loading up the DB too much.
Now, my query could be causing the problem, or it could be that Excel is starting to run multiple connections at once. Some evidence for this is the screenshot below and the fact that the load on the database appears to increase with time.
How do I establish a DB connection without constantly creating new connections?
Has anyone had similar problems working with Excel DB macros?
UPDATE
While the answers below were very useful (especially for someone starting out in VBA), it seems that the main reason my query was taking up load was a combination of multiple connections and having overlooked a line in my code:
With Sheets("FVols").QueryTables.Add(Connection:=rec1, Destination:=Sheets("FVols").Range("A1"))
.name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=True <<<<<<<<<<<<<<<<<<<<<<<-----
End With
You only need to open the connection once. That literally means you can execute multiple queries on that one active connection. You must close the connection and free the reference (specially with ADODB) to avoid running into collisions and other connection related problems.
If you know the queries you are going to be executing you can create an array (or collection) and add queries to the queue.
While you already have an open connection to work with you can keep executing queries.
Scan through code there is not much difference between yours and mine so you should be able to see what is going on and where. Please, ask questions in the comments if anything is unclear
Sub DbConnection()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="
cn.Open strConn
Dim queryArr, i
queryArr = Array("SELECT * FROM [MyTable]", "SELECT * FROM [MyOtherTable]")
For i = LBound(queryArr) To UBound(queryArr)
ExecuteQuery queryArr(i), cn, rs
Next i
cn.Close
Set cn = Nothing
End Sub
Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open CStr(query)
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
End Sub
Now, you only need to execute the DBConnection() once and all the queries you listed in the array will be executed.
Alternatively, if your queries are created at run-time you can pass it to the DbConnection() as a parameter.
Sub DbConnection(queryQueue As Collection)
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=HELIUM\PRI; Database=sourcedata; UID=tabula; PWD=Tabula123!"
cn.Open strConn
For i = 1 To queryQueue.Count
ExecuteQuery queryQueue.Item(i), cn, rs
Next i
cn.Close
Set cn = Nothing
End Sub
Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open CStr(query)
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
End Sub
Update:
You can declare your connection as a Global Variable. Now you can run the DBConnection() as many times as you like and you will not be creating a new connection each time. Instead you will be using the global connection object.
Option Explicit
Public cn As ADODB.Connection
Sub DbConnection()
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="
cn.Open strConn
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open "SELECT * FROM [MyTable]"
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Are you releasing the connection variable when you've finished with it? i.e.
Set rec1 = Nothing
The connection won't close fully if not.

DB2 connection from excel macro

I want to connect to DB2 from excel macro...This is my code, but it not working, Its giving error as 'Run-time Error'...Can anyone help me...
Option Explicit
Dim DBCONSRT, QRYSTR As String
Dim DBCON, DBRS As Object
Private Sub query()
DBCONSRT = "Driver=jdbc:db2://my_host;Database=PRTHD;hostname=NZ1;port=5355;protocol=TCPIP; uid=my_user;pwd=my_pass"
'CHANGE THE BELOW QUERY STRING ACCORDING TO YOUR NEED
QRYSTR = "select * from PRTHD.STRSK_OH_EOO"
Set DBCON = CreateObject("ADODB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open
'BELOW CODE USED TO GET THE DATABASE CONECTION AND EXECUTE THE QUERY CHANGE ACCORDIGN TO YOUR NEED
Set DBRS = CreateObject("ADODB.Recordset")
With DBRS
.Source = QRYSTR
Set .ActiveConnection = DBCON
.Open
End With
End Sub
Edit: I have changed my code to the following, but I'm still getting an error. The Error is "cant create Object"..Can ayone help me..
Dim DBCONSRT, QRYSTR As String
Dim DBCON As Object
Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=PRTHD;"
DBCON = CreateObject("OLEDB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open()
End Sub
The JDBC functionality I am pretty sure is not supported through vba and I think you need to use ODBC connectors to connect to DB2 if you are trying to integrate it into excel.
Private Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;In‌​itial Catalog=PRTHD;"
Using connection = New OleDbConnection(DBCONSRT )
connection.Open()
Dim cmd = connection.CreateCommand()
cmd.CommandText = QRYSTR //This is where your sql statement should go, or the variable that is equal to the query.
Using dr = cmd.ExecuteReader()
//Process your query results here
End Using
End Using
End Sub
Start with changing
DBCON = CreateObject("OLEDB.Connection")
to
Set DBCON = CreateObject("ADODB.Connection")
If you still get an error, double-check your connection string.