Use SQL to Query another excel file - excel

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

Related

Excel crashes following ADO connection

I'm trying to query a large named range within Excel
The following connection works well but is very slow when the range contains thousands of rows. Moreover, it seems that there is a limit on the number of records.
strCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFile & ";" & _
"Extended Properties=""Excel 8.0;"""
I'm trying to use a different connection but then, VB6 crashes!
myRangeName = "namedRangeWorksheet"
xlapp.Names.Add Name:=myRangeName, RefersTo:=TrueUsedRange
'**********************************
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = oWB.FullName
Set strCon = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strCon.Open "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = " & strFile & ";" & _
"Extended Properties = ""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
strSQL = "SELECT * from namedRangeWorksheet" ''Named range
rs.Open strSQL, strCon, adOpenKeyset, adLockOptimistic
Microsoft.ACE.OLEDB.12.0 works well on my computer when applied to Access database

Use ADODB to INSERT INTO specific table in an Excel workbook

I'm trying to use ADODB to execute a SQL INSERT INTO command into an Excel worksheet. I was able to insert into the worksheet when there was only one column in the worksheet using this code:
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim Connection As ADODB.Connection
Set Connection = New ADODB.Connection
Connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=PathToFile.xls;Extended
Properties=Excel 8.0;"
Connection.Open
Dim SQL As String
SQL = "INSERT INTO [Sheet1$] VALUES('Test')"
Call Connection.Execute(SQL, , CommandTypeEnum.adCmdText Or ExecuteOptionEnum.adExecuteNoRecords)
But I want to have three separate tables in the same worksheet and specify which of the tables to insert into. How can I do this? I tried creating the tables, naming them, and using this SQL statement to specify a table but I kept getting the error: The Microsoft Jet database engine could not find the object 'TestTable1'. Make sure the object exists and that you spell its name and the path name correctly.
SQL = "INSERT INTO TestTable1(ID) VALUES('test')"
You can do something like this:
Sub TestInsert()
InsertRecords Sheet4.Range("B3").CurrentRegion, _
"insert into # values('AAA','BBB','CCC')"
InsertRecords Sheet4.Range("F3").CurrentRegion, _
"insert into # values('ZZZ')"
InsertRecords Sheet4.Range("H3").CurrentRegion, _
"insert into # values('Whirled',99999)"
End Sub
Sub InsertRecords(rng As Range, sSQL As String)
Const S_TEMP_TABLENAME As String = "SQLtempTable"
Dim oConn As New ADODB.Connection
Dim sPath
'name the selected range
On Error Resume Next
ThisWorkbook.Names.Item(S_TEMP_TABLENAME).Delete
If Err.Number <> 0 Then Err.Clear
On Error GoTo haveError
ThisWorkbook.Names.Add Name:=S_TEMP_TABLENAME, RefersToLocal:=rng
sPath = ThisWorkbook.Path & "\" & ThisWorkbook.Name
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sPath & _
";Extended Properties=""Excel 8.0;HDR=Yes"""
oConn.Execute Replace(sSQL, "#", S_TEMP_TABLENAME)
Exit Sub
haveError:
MsgBox Err.Description
End Sub
Before:
After:

Getting errors while trying to open a Excel file with ADO

I'm trying to get some values from an Excel file (.xls) using ADO with SQL queries. However I'm getting error while trying to open the connection. This is what I have currently:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = IIf(strPath <> "", strPath, Range("G13").Value)
If strFile = "" Then Exit Sub
strCon = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";'Extended Properties='Excel 8.0;HDR=No;IMEX=1';"
strCon2 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & ";'Extended Properties='Excel 12.0 Xml;HDR=YES';"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon2
I have tested using both my connection strings (strCon, strCon2) with no success. I either get an error with no text only an "x" symbol. Or a "System Error &H80004005 (-2147467259)"
Edit:
Changed it so I open recordset instead, however it still gives me the same error.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = IIf(strPath <> "", strPath, Range("G13").Value)
If strFile = "" Then Exit Sub
strCon = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & _
strFile & "';'Extended Properties='Excel 8.0;HDR=No;IMEX=1';"
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFile & ";" & _
"Extended Properties=Excel 12.0;"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
'cn.Open strCon
strSQL = "SELECT * FROM [Sheet11$C5]"
rs.Open strSQL, strConn
Debug.Print rs.GetString
It's too late to answer this question, but for future readers.
I had a similar problem.
I tried to connect Excel with MySQL database, but when the recordset open, it cracks and shows me the &H80004005 error.
Finally, the problem was my office is 32 bits but my ODBC was 64 bits and this did not like it.
I changed the ODBC connection to 32 bits and the VBA function worked.

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)

Is there a way to use OLE DB Provider for Jet on an unsaved Excel workbook?

I am working with the Microsoft OLE DB Provider for Jet to execute queries on spreadsheets in Excel using VBA. Is there a way to execute the following code on an unsaved workbook?
For example, ActiveWorkbook.FullName returns "Book1" if the workbook has never been saved. In that case the Data Source will assume the path is the active directory, and error out because the file was never saved.
Is there any way to use the Excel temporary file as the Data Source for Jet? I would like to test this but I don't even know how to return the Path and Name for the Excel temporary file.
Public Sub LocalJetQuery()
Dim objStartingRange As Range
Dim objConnection As New ADODB.Connection
Dim objRecordset As New ADODB.Recordset
Dim strDSN As String
Dim strSQL As String
Set objStartingRange = Application.Selection
If CLng(Application.Version) >= 12 Then
strDSN = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & objStartingRange.Worksheet.Parent.FullName & ";" _
& "Extended Properties=""Excel 12.0 Xml;HDR=No;IMEX=1"";"
Else
strDSN = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & objStartingRange.Worksheet.Parent.FullName & ";" _
& "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"
End If
strSQL = "SELECT * FROM [" & objStartingRange.Worksheet.Name & "$];"
objConnection.Open strDSN
objRecordset.Open strSQL, objConnection
Application.Workbooks.Add(xlWBATWorksheet).Sheets(1).Cells(1, 1).CopyFromRecordset objRecordset
End Sub
Thanks!
No. Just like David Fenton says in the comments.

Resources