SQL Query Automation Error - excel

I am trying to run a query to search for data in Microsoft Access and am running into a bit of a problem. The error occurs on the line
rec.Open sqlQuery, conn
and reads "Run-time error '-2147217900 (80040e14)': Automation error"
Sub query21st()
' create file path reference string for 21st data
dbPath = database_path()
' create connection string
Dim connString As String
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath & ";" & _
"Persist Security Info=False;"
'create connection with connection string from above
Dim conn As New ADODB.Connection
conn.Open connString
' create sql command string
Dim lookupFields As String
lookupFields = "cert.[avgle]"
Dim sqlQuery As String
sqlQuery = "select " & lookupFields & " from [Certificates] as cert " & _
"where [DOB] =" & [dob_21st] & " AND [CertificateDate] =" & [certdate_21st] & " AND [MPI1] =" & [mm] & ")"
' create recordset and get data from connection
Dim rec As New ADODB.Recordset
rec.Open sqlQuery, conn
[returnRange_21st].ClearContents
[returnRange_21st].Cells(1).CopyFromRecordset rec
' close recordset
rec.Close
'close connection
conn.Close
End Sub
The "database_path" function contains delicate info that cannot be posted but I guarantee it works just fine. Any help would be greatly appreciated.

Related

how do i use ADODB connection in vba

I need data by array
Target file is on the network and data value added in a 10 sec
Need to connect to this file (.xls) and make a real time chart
Now the problem is how do I use ADODB for this opened file
2 case happen:
1st:
dim path as string, DB as string
dim cnt as ADODB.Connection
OLEDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & DB & ";
extended properties=""excel 12.0 xmlHDR=YES"";"
Set cnt = New ADODB.Connection
cnt.Open OLEDB
Then i got "cant find ISAM installation" error
2nd:
dim path as string, DB as string
dim cnt as ADODB.Connection
OLEDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & path & DB &";
extended properties=""excel 8.0;HDR=YES;IMEX=1;';"""
Set cnt = New ADODB.Connection
cnt.Open OLEDB
Then I got 3706 runtime error, cant find supporter
So what is wrong with me?
This is how I usually get it running:
DbConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & path & ";" & _
"Extended Properties=""Excel 12.0; HDR=YES"";"
Where path is the full file path + file name.
You can find more Informations on Connection strings here
Worksheet name and Range then go in the SQL Statement. For example:
sqlWhere = sheetName & "$A1:$Z1000"
DbRecSet.Open "SELECT * FROM [" & sqlWhere & "]", DbConn, adOpenStatic
Edit:
If i understand you correctly,
you have a single cell that changes value every 10 seconds and you want to get that value via ADODB.
First of all, in this case, you can scrap HDR=YES from the connection string.
let's say that cell is A1
sqlWhere = sheetName & "$A1"
DbRecSet.Open "SELECT * FROM [" & sqlWhere & "]", DbConn, adOpenStatic
returnValue = DbRecSet.Fields(0)
path = test_fdr & "" & today_total & ".xls"
OLEDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & path &
";Extended Properties=""Excel 8.0;HDR=YES"";"
Set cnt = New ADODB.Connection
cnt.Open OLEDB
Rcdset.Open Source:="[" & TestSheetName & "$]", _
ActiveConnection:=cnt, _
CursorType:=adOpenStatic, _
LockType:=adLockReadOnly, _
Options:=adCmdTable
With Sheets(3).QueryTables.Add(Connection:=Rcdset, Destination:=Target_rng)

Use SQL to Query another excel file

I'm try an alternative to solve this issue using VBA to get the data.
The following code works fine when "Tbltest" is a range but not working when the name represent a table. How can I make it work with Table not range.
Function ConnectToExelPRJReview()
Dim Xlpath As String
On Error GoTo ErrHandlerconnection:
Dim Xlcn As ADODB.Connection
Dim Xlrs As ADODB.Recordset
Xlpath = "\\xxx.xxx.xxxxxx.net\project_review\wip\" & "filetotest.xlsm"
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Xlpath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set Xlcn = CreateObject("ADODB.Connection")
Set Xlrs = CreateObject("ADODB.Recordset")
Xlcn.Open strCon
strSQL = "SELECT * FROM [Tbltest]"
Xlrs.Open strSQL, Xlcn
'display the first data
MsgBox Xlrs.Fields(0).Value
Xlcn.Close
Exit Function
ErrHandlerconnection:
MsgBox Err.Number & " " & Err.Description, vbCritical, "EXCEL CONNECTION ERROR"
End Function

Replace Worksheets content without opening it

I am using ADO model to gather data from various closes workbooks. This is working well.
I now want to put this data in another closed workbook, but I would like to be able to delete a sheet content before.
How can I delete a worksheet content without opening the workbook using VBA ?
How can I transfer a record set to a closed wb ? / Copy one table to another using ADO ?
EDIT :
I was able to insert some data from one workbook to another one in a new sheet but I can't get to output data in an existing worksheet.
When I try the INSERT INTO statement, an error is raised. Update impossible, database or object readonly.
Here is the code :
Sub tranfert()
Dim ExcelCn As ADODB.Connection
Dim ExcelRst As ADODB.Recordset
Dim Cn As New ADODB.Connection
Dim Rst As New ADODB.Recordset
Dim maBase As String, maFeuille As String
Dim maTable As String, NomClasseur As String
Dim nbEnr As Long
maBase = "C:\Users\Lichar\Documents\Base.xlsx"
maTable = "[table$]"
NomClasseur = "C:\Users\Lichar\Documents\Target.xlsx"
maFeuille = "Sheet2"
'Connection to base file
Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & maBase & ";" & _
"Extended Properties=""Excel 12.0;HDR=NO;"""
'Requète dans la table Access
Rst.Open "SELECT * FROM " & maTable, Cn
'Connection to target file
Set ExcelCn = New ADODB.Connection
ExcelCn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & NomClasseur & ";" & _
"Extended Properties=""Excel 12.0;HDR=NO;"""
'-----------------------------------------
'Create a new sheet and output data
Cn.Execute "SELECT * INTO [Excel 12.0;" & _
"Database=" & NomClasseur & "].[" & maFeuille & "] FROM " & maTable, nbEnr
'-----------------------------------------
'Trying to ouput data in existing sheet
'Cn.Execute "INSERT INTO [sheet$] IN '' [Excel 12.0;" & _
' "Database='" & NomClasseur & "'] SELECT * FROM " & maTable, nbEnr
Rst.Close
Cn.Close
Set ExcelRst = Nothing
Set ExcelCn = Nothing
**EDIT 2 **
I've found a partial solution using INSERT INTO. Here is a working code that takes data from source.xlsx in the table sheet and output it (or append) in target.xlsx in the sheet sheet :
Sub SQLQUERY()
Dim Cn As ADODB.Connection
Dim QUERY_SQL As String
Dim Rst As ADODB.Recordset
Dim ExcelCn As ADODB.Connection
Dim ExcelRst As ADODB.Recordset
SourcePath = "C:\Users\BVR\Documents\Source.xlsx"
TargetPath = "C:\Users\BVR\Documents\Target.xlsx"
CHAINE_HDR = "[Excel 12.0 MACRO;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] "
Set Cn = New ADODB.Connection
STRCONNECTION = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & SourcePath & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0 Macro;"";"
QUERY_SQL = _
"SELECT * FROM [table$] "
Cn.Open STRCONNECTION
Set ExcelCn = New ADODB.Connection
ExcelCn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & TargetPath & ";" & _
"Extended Properties=""Excel 12.0;HDR=NO;"""
Cn.Execute "INSERT INTO [sheet$] IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL
'--- Fermeture connexion ---
Cn.Close
End Sub
I've noticed 2 problems. First If one of my field name contains a "." in it, the code will generate an error stating that INSERT INTO contains an unknown field name. This is problematic.
Second I cannot select only the columns I want. If I "SELECT [F1], [F2] ..." an error will raise stating that there is a circular reference. (I can however select the columns I want using field names)

Unspecified error when opening the 65th ADODB Recordset in a loop

I have a bit of code that loops through a bunch of files in a folder and loads the data into recordsets, storing the filenames and recordsets in a dictionary (as a key/value pair) for later use. The loop works fine for the first 64 files, but then it gives me an "Unspecified Error" dialog on the 65th try. The code breaks at the recordData.Open line (the loop calls the below function, so the For Each loop is not shown):
Public Function GetRecords(ByVal dataSrc as String) as ADODB.Recordset
Dim dir as String
Dim file as String
Dim recordData as ADODB.Recordset
Dim sql as String
Dim conn as String
dir = "C:\MyDirectory"
file = dataSrc & ".csv"
conn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & dir & ";" & _
"Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;"""
If DoesFileExist(dir & file) Then
sql = "select * from " & file & ";"
Set recordData = New ADODB.Recordset
recordData.CursorLocation = adUseClient
recordData.Open sql, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
Else
Set recordData = Nothing
End If
Set GetRecords = recordData
recordData.Close
End Function
If I rename or delete the file it currently stops on, it errors out on the new 65th file, so I know the actual file itself is not to blame. Is there a limitation on the number of recordsets that I can open in one session, or am I opening them in an inefficient way?
Well, after tinkering with it, I discovered the problem lay in the connection. Instead of constructing the connection string as a string, I created a connection object and then closed it after opening the recordset. Must be some kind of limitation on the number of connections that can exist in a given session. Here is the revised function:
Public Function GetRecords(ByVal dataSrc as String) as ADODB.Recordset
Dim dir as String
Dim file as String
Dim recordData as ADODB.Recordset
Dim sql as String
Dim cn as ADODB.Connection
dir = "C:\MyDirectory"
file = dataSrc & ".csv"
If DoesFileExist(dir & file) Then
sql = "select * from " & file & ";"
Set recordData = New ADODB.Recordset
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & dir & ";" & "Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;"""
.CursorLocation = adUseClient
.Open
End With
recordData.CursorLocation = adUseClient
recordData.Open sql, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
cn.Close
Else
Set recordData = Nothing
End If
Set GetRecords = recordData
recordData.Close
End Function

copying data from Sql Db in excel on basis of date and db taken from user

I am making some macro and taking datea and db from the user. and on that basis i am fetching the data from db.
here is my code please take a look and share if any solution you have for this.
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Function GetConnectionString() As String
Dim strCn As String
strCn = "Provider=sqloledb;"
strCn = strCn & "Data Source=" & Range("Server") & ";"
strCn = strCn & "Initial Catalog=" & Range("Database") & ";"
If (Range("UserID") <> "") Then
strCn = strCn & "User ID=" & Range("UserID") & ";"
strCn = strCn & "password=" & Range("Pass")
Else
strCn = strCn & "Integrated Security = SSPI"
End If
GetConnectionString = strCn
End Function
Sub Test()
ActiveWorkbook.Sheets("Sheet1").Activate
Dim ws As Worksheet
Dim Sql As String
Dim d As String
d = Range("A2").Value
d = Format(d, "yyyy-mm-dd")
cn.ConnectionTimeout = 100
cn.Open GetConnectionString()
Sql = "select * from config where convert(date,logadate,103)='"& d &"'"
ExecInsert (Sql)
Set rs.ActiveConnection = cn
rs.Open Sql
ActiveWorkbook.Sheets("Sheet2").Activate
Dim ws1 As Worksheet
**Range("A2").CopyFromRecordset (rs)**
cn.Close
End Sub
Sub ExecInsert(selectquery As String)
'End Sub
Dim cmd As New ADODB.Command
cmd.CommandText = selectquery
cmd.CommandType = adCmdText
cmd.ActiveConnection = cn
cmd.Execute
End Sub
Range("A2").CopyFromRecordset (rs) this is where i'm getting error
run type error '430' class does not support automation or does not support expected
interface
i have all the dlls and registered them as well. and even no reference is missing from my end.
if any body have face this issue please help...
SQL Server does not have a function called Format (MS Access and VB does).
In SQL Server you would use Convert (first verify that the SQL Server datatype is datetime, not varchar or char)
Or if your datepicker returns data in the correct format you can just add it straight in:
q = q & " where logdate='" & d & "'"
Be aware that if you have a time component you need to strip it out.
So...
Try the code above
Verify that the database is SQL Server and the datatype is DATETIME
Inspect the contents of your datepicker as a string and verify it's format

Resources