DB2 connection from excel macro - vba

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.

Related

Excel Azure SQL Server execute command error

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

VBA(AUTOCAD) SQL query to store String Values

I have a small issue, I am trying to code a Macro for Autocad in VBA.
I am trying to read a certain column value through sending a SQL native query that connects to the database server.
The problem is that my String variable descToReturn that's going to hold a value of that column is returning null. I can't seem to figure out where I am wrong. So if anyone can advise that'd be great.
Here's the code below:
Private Sub btnDuplicate_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim BOMLineToCheck As AcadBlockReference
Dim BOMAttributes As Variant
Dim partNoToCheck As String
Dim i As Integer
Dim descToReturn As String
ConnectionString = "Provider=SQLxxxxx.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xx\xx;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=xxx_xxx"
Set cnn = New ADODB.Connection
cnn.ConnectionString = ConnectionString
cnn.Open
'cnn.CommandTimeout = 900
Set rst = New ADODB.Recordset
StrQuery = "SELECT * FROM [My Table Name] WHERE [My Column]='partNoToCheck'"
For Each BOMLineToCheck In ThisDrawing.ModelSpace
If BOMLineToCheck.Name = "BOM3LINE_old" Then
BOMAttributes = BOMLineToCheck.GetAttributes()
For i = 0 To UBound(BOMAttributes)
If BOMAttributes(i).TagString = "PART#" Then
partNoToCheck = BOMAttributes(i).TextString
End If
Next i
End If
rst.Open StrQuery, cnn, adOpenDynamic
With rst
If Not .EOF Then
descToReturn = rst![My Coulmn]
End If
End With
rst.Close
MsgBox descToReturn
Next
End Sub
Look closely for a typo:
descToReturn = rst![My Coulmn]
You probably mean:
descToReturn = rst![My Column]
See the difference?
So, I found the answer, because I am bringing SQL within VBA environment, the syntax was not right and its a weird syntax:
correct Syntax for SQL query:
StrQuery = "SELECT * FROM [My Table] WHERE [My Column]= '" & partNoToCheck & "'"

Vba Excel ADODB pre-load in cash dataset to query faster a big Access dataset 500000 rows

Good afternoon
I have an issue: speed in Excel retrieving data from Access external database
(47 sec. --> I want to reach 3 seconds)
Excel 2010
Access 2000
Code at the opening event I open I run this macro:
'I define connection and dataset as public
Public conn As ADODB.Connection
Public mrs As ADODB.Recordset
Public cmd As ADODB.Command
Public DBPath As String
Public strConn As String
Public strSQL As String
Public Sub preloadDataset()
Set conn = New ADODB.Connection
Set mrs = New ADODB.Recordset
DBPath = ThisWorkbook.Path & Application.PathSeparator & "Exported.mdb"
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data source=" & DBPath
.Open
End With
Set cmd = New ADODB.Command
strSQL = "SELECT * FROM [Database_5000Rows] WHERE "PrNameHelp" = ? AND "ScCompHelp" LIKE ""%?%""
Set cmd.ActiveConnection = conn
cmd.CommandText = strSQL
cmd.CommandType = adCmdText
cmd.Prepared = True
'MANUAL creation of parameters
cmd.Parameters.Append cmd.CreateParameter("PrNameHelp", adLongVarChar, adParamInput)
cmd.Parameters.Append cmd.CreateParameter("ScCompHelp", adLongVarChar, adParamInput)
End sub
The main macro:
Public Sub ADO_retrieve_Ext_file()
cmd("PrNameHelp") = str01
cmd("ScCompHelp") = str02
cmd.Execute
Application.Calculation = xlCalculationManual
Sheet1.Range("A1").CopyFromRecordset mrs
Application.Calculation = xlCalculationAutomatic
End sub
In the closing event:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'**********************
''Close Recordset
mrs.Close
''Close Connection
conn.Close
Set mrs = Nothing
Set Conn = Nothing
'**********************
End sub
How can I define parameters taking care of SQL correct string for Access ?
Is it the correct method using parameters or it is better to upload in RAM the whole database?
Thank you
Enrico
When copying your data to the sheet, try to avoid update it until you finish. Use:
Application.ScreenUpdating = False
and
Application.ScreenUpdating = true
SOLVED: programmatically indexed the first column of the table in Access

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.

Connect Excel to Access - VBA

I get a "User-defined type not defined" error when I execute the below code, and the
"objCon As ADODB.Connection"
is highlighted on the first line.
I am trying to set a connection from Excel to Access via VBA code. Thank you for any advice!
Private objCon As ADODB.Connection
Private rstRec As ADODB.Recordset
Private strQry
Sub Connect()
Dim strConn As String
Set objCon = New ADODB.Connection
objCon.Mode = adModeReadWrite
If objCon.State = adStateClosed Then
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "C:\DB\Db.accdb;Persist Security Info=False;"
objCon.ConnectionString = strConn
objCon.Open
End If
End Sub
You can do one of the following
set objCon = CreateObject("ADODB.Connection")
set rstRec = CreateObject("ADODB.Recordset")
Or in VBA Editor
Tools-->Reference-->
Add Microsoft ActiveX Data Object X.Y Library