ADODB connection parameter issue - vba

I am getting error as
Too few parameters expected 1
on below line. Please assist
mrs.Open sSQLSting, Conn, 3, 1
Complete coding
Dim Conn As New adodb.Connection
Dim mrs As New adodb.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLSting = "SELECT * From [DataSheet$A1:D5325] where [Vertical Name]= '" & Sheets(1).ComboBox1.List(i) & "'"
mrs.Open sSQLSting, Conn, 3, 1
Sheets("Sheet4").Cells(lastrow, 4).Value = mrs.RecordCount
mrs.Close
Conn.Close

Yes the error message is not very intuitive :(
That is because when the field names in your SQL query do not match the table fields name:
Too few parameters expected 1
means that 1 filedname that you are using in your SQL-Statement is not available in your table.
So probably a field called Vertical Name does not exist!
I also highly recommend to use Option Explicit and declare all your variables properly to avoid mistyping in variable names: Eg. sSQLSting was obviously meant to be sSQLString. If you don't use Option Explicit you will run into issues soon.

Further to my comment, I have mocked up some dummy data, and the following works
Sub Data_Extract()
Dim c As New ADODB.Connection
Dim r As New ADODB.Recordset
Dim s As String
s = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Workspace\Dummy Data\SAMPLE_GENERAL.xlsx;" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
c.Open s
r.Open "Select * from [Sheet1$A1:E5] where [field 1]='b'", c, 3
End Sub

Related

How to merge two workbooks with one common column using SQL in VBA

I believe i can do this through Macro as well but i would like to get introduced to ADODB and SQL queries in VBA. The datasets are not in Access but separate workbooks and the SQL query for the two workbooks are as follows:
SELECT getRollpHierRpt.Field1, ['App].[Master Book Name], ['App].[App Book Name], ['App].[Secondary App Book Name], ['App].[App Code], ['App].[App Book Status], ['App].[Book Transit], ['App].[Transit Desc], ['App].[Legal Entity Id], ['App].[Legal Entity Desc]
FROM ['App] INNER JOIN getRollpHierRpt ON ['App].[Book Transit] = getRollpHierRpt.Field1;
The examples i have seen on internet include getting a connection to Access/SQL server but if the datasets are two excel workbooks?
Sub MergeIt()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
With conn1
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\amzubaid\Desktop\Practice Merging\13-10-2017.xlsm;" &
"Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
.Open
End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\amzubaid\Desktop\Practice Merging\20181015-Practice.xlsm;" & "Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
.Open
End With
Dim rsSmall As New Recordset
rsSmall.Open "select [Field1] from [getRollpHierRpt$]", conn1
Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell
rsBig.Open "select [App Code],[Legal Entity Desc]," & rsSmall("Field1") & "
As GetRollPH from [getRollpHierRpt$] where [BookTransit] = " &
rsSmall("Field1"), conn2
r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF 'end if file
rsSmall.Close
conn1.Close
conn2.Close
End Sub
You will need to set a connection to each workbook. In effect this relies on treating each workbook as a table in a database. You must have column headings in each workbook, which are treated as field names. Try this for details
OK So it doesn't seem possible - so one possible workaround is to open the smaller table and then step through it and use the individual values to retrieve the desired records from the larger table: Here's an example using two workbooks called Testfile1 and testfile2. Each contains a sheet called "test" and some data with column headings in testfile2 called "TestC" and "TestD" and the first (linking) filed in testfile1 called "TestA". (This requires a reference to Microsoft Active X Data Objects" library in VBE, Tools, References)
Sub TwoFiles()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
With conn1
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile1.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
.Open
End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile2.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
.Open
End With
Dim rsSmall As New Recordset
rsSmall.Open "select [testA] from [test$]", conn1
Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell
rsBig.Open "select [TestC],[TestD]," & rsSmall("testA") & " As GetRollPH from [test$] where [testC] = " & rsSmall("testA"), conn2
r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF 'end if file
rsSmall.Close
conn1.Close
conn2.Close
End Sub

How to connect to Netezza (PureData System for Analytics) via VBA

I am trying to connect to connect to Netezza using VBA. I have enabled the following:
Microsoft Excel 15.0 Object Library
Microsoft Office 15.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Visual Basic for Applications
Here is my code:
Sub NZConn()
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim x As Variant
Set cmd = New ADODB.Command
Set RS = New ADODB.Recordset
cmd.ActiveConnection = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.CommandTimeout = 120
cmd.CommandType = adCmdText
x = "Write Query here"
cmd.CommandText = x
Set rs = cmd.Execute
Sheet1.Range("A1").CopyFromRecordset rs
cmd.ActiveConnection.Close
End Sub
I can get the code to run without throwing back an error, but there is nothing that is pasted from the record set, which leads me to believe that is may have something to do with the structure of the connection string.
I have the server, user id, password, database, port, and driver.
Would I need to establish / open an ActiveConnection first?
I was able to figure out the issue on my own. I found that there is a command line builder in the 'Tools' tab in Aginity, which helped specify the exact connection string I needed to connect to Netezza. Once I had this connection string, I was getting an 'architecture mismatch' error. After downloading the 32-bit ODBC drivers for Netezza, the methodology worked perfectly. Here is the updated code below:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String, ConnectionString As String
Dim Server As String, Query As String
Dim SQLTable As Worksheet
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Set SQLTable = Sheet1
Server = SQLTable.Cells(2,3).Value
User = SQLTable.Cells(2,4).Value
PW = SQLTable.Cells(2,5).Value
DB = SQLTable.Cells(2,6).Value
Query = SQLTable.Cells(2,7).Value
ConnectionString = "Driver={NetezzaSQL};" & _
"server=" & Server & ";" & _
"UserName=" & User & ";" & _
"Password=" & PW & ";" & _
"Database=" & DB & ";" & _
"Query Timeout=120"
cn.Open (ConnectionString)
rs.Open (Query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Worksheets("Sheet2").Cells(2, "A").CopyFromRecordset rs
rs.Close
cn.Close
NB:
"IBM NETEZZA ODBC DRIVER – 32 BIT" is what I downloaded
"ODBC-DRIVER-FOR-NETEZZA-7-X86" is what showed up in my software center to install
"Name: NetezzaSQL ; Version: 7.00.04.41188 ; Company: www.ibm.com ; File: NSQLODBC.DLL" is what is shown now in my 32-bit 'ODBC Data Source Administrator' window
I think your connection string is ok, and yes you should need to open a connection first.
Like this:
AccessConnect = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
Dim Conn1 As New adodb.Connection
Conn1.ConnectionString = AccessConnect
Conn1.Open
then it would be
Set RS = Conn1.Execute(x) 'where x is your query

How to resolve 'Timeout expired' error while connecting to External (ODBC) database in MS Access?

I am working on an Access application which needs to establish a connection to an External database (Netezza database). I am currently using VBA code with ADODB objects to connect to the server.
Whenever I execute the code, 'Timeout expired' error occurs.
I have tried to reset the Timecounter to 180 seconds. Still the error is not resolved.
This is the code I've been using:
Private Sub CONNECT_Click()
Dim openSQL As ADODB.Connection
Set openSQL = New ADODB.Connection
openSQL.ConnectionTimeout = 180
openSQL.Open "odbc;servername=xxx;dsn=xxx;database=xxx;uid=xxx;pwd=xxx;port=xxx"
openSQL.Close
End Sub
I've also tried the below code:
Private Sub Modify_Click()
Dim objConnection As ADODB.Connection
Dim objRecordSet As ADODB.Recordset
Dim strConnectionString As String
Set objConnection = New ADODB.Connection
Set objRecordSet = New ADODB.Recordset
'Define the Odbc connection string.
strConnectionString = "odbc;servername=xxx;dsn=xxx;database=xxx;uid=xxx;pwd=xxx;port=xx"
'Instantiate the Connection object and open a database connection.
'var cnn
objConnection.Open strConnectionString
'objConnection.Open "dsn=xxx;User ID=xxx;Password=xxx"
Dim strSQL As String
'Define SQL SELECT statement.
strSQL = "INSERT INTO Table_1 (col1,col2,col3, col4) VALUES ('" & Form1.col1 & "', '" & Form1.col2 & "', '" & Form1.col3 & "', '" & Form1.col4 & "');"
'Use the Execute method to issue a SQL query to database.
cnn.Execute strSQL
End Sub
Thanks in advance!

VBA / ADO QUERY Runs on my computer and fails on coworkers computer

The following code works perfectly fine on my computer. I cannot understand why it's not working on another persons computer. Can someone lead me towards ideas that may help trouble shoot this?
The error (with on error commented out) is that the array isn't being loaded with data. Get an error like "either bof or eof is true for the current record"
Also I can tell you if the on error GoTo NEXTT is left on.. it goes there and tries to erase the array and returns a wrong data type error. Makes me think the array is empty.
I checked Conn.State and I can confirm that the connection is open.
Function sbADO(ban_id, upc_id, div_id)
'Must add Activex data objects libaray 2.8
Dim sSQLSting As String
On Error GoTo nextt
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
'You can provide the full path of your external file as shown below
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Conn.Open sconnect
sSQLSting = "SELECT * From [data$] where BANNER_ID IN (" & ban_id & ") AND UPC_ID IN (" & upc_id & ") AND DIVISION_ID IN (" & div_id & ") " 'Your SQL Statemnt (Table Name= Sheet Name=[DataSheet$])
mrs.Open sSQLSting, Conn
'=>Load the Data into an array
ReturnArray = mrs.GetRows
''OR''
'=>Paste the data into a sheet
'Sheets("Sheet1").Range("A2").CopyFromRecordset mrs
'Close Recordset
mrs.Close
'Close Connection
Conn.Close
'
Exit Function
nextt:
Erase ReturnArray
'mrs.Close
Conn.Close
'MsgBox (ReturnArray(6, 2)) '(feild, row)
End Function
The problem is because
DBPath = ThisWorkbook.FullName <-- the workbook is set to read only.
Removing read only status fixes the issue.
It seems like you're using ADO to query data in the same workbook? That might be for the purposes of simplifying this problem for SO, but it would be easier and faster to get the array you need by referring to the range directly. But in this answer, I'll assume that you really do want to use ADO.
You're trying to use ADO to open the workbook, but you're not specifying the ConnectionString or Open methods with any read-only arguments. Try making these adjustments:
'Add Mode=Read
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";Mode=Read;"
'Add adLockReadOnly
mrs.Open sSQLSting, Conn, , adLockReadOnly

Select Statement for Excel Datasource

I am connected to Excel sheet, which is acting as database. I need to select some records with where condition but I am getting error:
No value given for one or more required parameters
by using below code:
Dim conn As Object
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set conn = CreateObject("ADODB.Connection")
XLName = "C:\Users\X\Desktop\rawdata.xlsx"
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" &
XLName & "';Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"
conn.Open connString
rs.Open ("SELECT * FROM [data$] where industry='Government'"), conn,
adOpenDynamic, adLockReadOnly
Sheet1.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close
When you set HDR=NO the column titles from the excel table will be ignored and it will be used internal names. See older answer: c#, oledb connection string issue