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)
Related
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
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)
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
I am trying to do a Join on 3 tables in Excel through VBA using Microsoft.ACE.OLEDB.12.0. Having lots of issues trying to get the query to run. At this point I get the following error:
Run-time error '-2147217865 (800040e37)':
The Microsoft Access database engine could not find the object 'CustomSheetName1$A$1:$AV$6027'. Make sure the object exists and that you spell its name and the path name correctly. If 'CustomSheetName1$A$1:$AV$6027' is not a local object, check your network connection or contact the server administrator.
The source file is created in the same sub and saved to the macro root folder located locally in C:\Users\localuser\Documents\MacroFolder\. I have full access to the file.
When run the connection string shows as:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\localuser\Documents\MacroFolder\Book4.xlsx;Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1';"
Extract of sub below. I have obfuscated the field names and only included code I thought was relevant. Can add more and clarify further if required. Code breaks at the last line when executing the query.
Dim wbTarget As Workbook, wsTarget As Worksheet
Dim wb As Workbook, ws As Worksheet
Set wbTarget = Workbooks.Add
Set wsTarget = wbTarget.Sheets.Add(After:=wbTarget.Sheets(wbTarget.Sheets.Count))
wsTarget.Name = "CustomSheetName1"
varFilePathElements = Split(ThisWorkbook.Path, "\")
strFileName = varFilePathElements(UBound(varFilePathElements))
Dim strWBTargetFullFileName As String
strWBTargetFullFileName = Replace(ThisWorkbook.Path, "strfilename", "") & "\" & wbTarget.Name & ".xlsx"
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strWBTargetFullFileName _
& ";Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1';"
strSQL = "SELECT " _
& "sh1.company_name, " _
& "sh1.company_type, " _
& "sh1.customer_no, " _
& "sh1.fk1, " _
& "SUM(sh3.total_stat) as total_stat, " _
& "FROM ( [CustomSheetName1" & wbTarget.Sheets("CustomSheetName1").UsedRange.Address & "] sh1 " _
& "LEFT JOIN [CustomSheetName2" & wbTarget.Sheets("CustomSheetName2").UsedRange.Address & "] sh2 " _
& "ON sh2.fk1 = sh1.fk1 ) " _
& "LEFT JOIN [CustomSheetName3" & wbTarget.Sheets("CustomSheetName3").UsedRange.Address & "] sh3 " _
& "ON sh3.fk2 = sh2.fk2 AND sh3.fk3 = sh2.fk3 " _
& "GROUP BY sh1.customer_no, sh1.company_name, sh1.company_type, sh1.fk1 " _
& "ORDER BY total_stat"
wbTarget.Sheets(1).Range("A1").Value2 = strSQL
wbTarget.SaveAs (strWBTargetFullFileName)
wbTarget.Close
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
rs.Open strSQL, cn, 3, 3
Any help would be greatly appreciated. Regards,
When reading Excel worksheets via ADO, the $ sign is appended to the end of the worksheet name, like this:
SELECT * FROM [Sheet1$]
Using the absolute range address adds extra $ signs that cause the worksheet name to be interpreted incorrectly. You need to use non-absolute range addresses to stop this happening. Adding some parameters to UsedRange.Address can fix this:
[CustomSheetName1$" & wbTarget.Sheets("CustomSheetName1").UsedRange.Address(False, False) & "]
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.