Using ADODB to access opened xls file - excel

Although I've been working with VBA for Excel for quite a long time, I've one problem I cannot solve by myself. I've described it below, hope to get some help or advice.
I'm using Excel 2007 and Windows XP, all updated with newest patches.
I'm very often using following code to get data from another workbook:
Set conn = New ADODB.Connection
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=g:\source.xls;Extended Properties=Excel 8.0;"
Sql = "SELECT Field1, Field2 FROM [Sheet1$]"
Set rst = New ADODB.Recordset
rst.Open Sql, conn, adOpenForwardOnly
Worksheets("Results").Range("A2").CopyFromRecordset rst
rst.Close
Set rst = Nothing
conn.Close
Set conn = Nothing
As simply as can be - just connect to file and get some data from it. It's working perfect as long, as the source file that is located on a common network drive (g:\source.xls) is not opened on another computer.
When some user on another computer has opened the file and I try to execute the following code, I notice one thing that I'd like to get rid off: the source Excel file is opened (in a read-only mode) on my computer and it's not closed after the connection to that file has been closed. What's worse, even if I close this source file manually, it leaves some garbage in my file, like it was never closed: see the picture after couple of code execution (the source files has been closed before):
I started to believe it's a bug that cannot be solved - hope I'm wrong :)

Your Excel version is 2007 or later?
if is use Microsoft.ACE.OLEDB.12.0 at provider and your problem is solved.
[]´s

This is actually a known bug, see: http://support.microsoft.com/default.aspx?scid=kb;en-us;319998&Product=xlw. Querying an open Excel workbook with VBA causes a memory leak to occur as the reference is not released even when closing the connection and clearing the object.

You would be much better to open your Excel data source using the built in Excel reference, rather than an ADO connection e.g:
Dim xlApp As New Excel.Application
Dim xlWrkBk As Excel.WorkBook
xlApp.WorkBooks.Open FILENAME
Set xlWrkBk = xlApp.ActiveWorkbook
And then go from here instead

Related

How to repair office DAO? (Or is it my fault excel crashes?)

I did following: A database connection over vba in excel (DAO) works both in office 356 and 2016. After setting a database password in Office 356 this db cannot be opened over DAO in Office 2016. (both same lib, Office Access 16 database engine object". So I set the password in Office 16, works now. After opening the file in Excel 356 again Excel crashes at an unexpected operation without error message. Now all other DAO connections in all files on this pc do not work anymore. (I think its just a random bug and hasn't anything to do with this password thing)
This error is actually reproducible on this pc.
I created a test.accdb and added one table with 2 fields and one record.
I created a test.xlsm and added following code:
Sub Test()
Dim db As DAO.Database
Set db = DAO.OpenDatabase(ActiveWorkbook.Path & "/test.accdb")
Dim ts As DAO.Recordset
Set ts = db.OpenRecordset("SELECT * FROM Tabelle1")
Dim myfield As DAO.field
If Not ts.EOF Then
For Each myfield In ts.Fields ' crash here
MsgBox myfield.Name
Next
End If
ts.Close
db.Close
End Sub
At exactly this line excel stops existing. Just press F8(next line) and back to desktop. Just away. No error. ts.Fields is not nothing as you can see in image.
I've restarted my system, no change. How to repair DAO database connections? Or is some problem in this code? The same files work like expected on my other pc.
EDIT: As noted correclty it is not wise to call the object "field" as Excel imports the namespace of DAO automatically. The error also occurs when naming it myfield.
EDIT2: The error found in system protocol is somehow unspecific: ACEDAO.DLL 0xc0000005
Thanks for your help. It was an MS Office error which was resolved after office reinstall.

ADO recordset crashes while evaluating EOF after Excel upgrade

I have an Excel sheet that connects to a Basis database using an ODBC connection. It worked fine when we were running Excel 2010 on Windows Server 2008, but then we upgraded to Excel 2016 on Windows Server 2016, and it doesn't work anymore.
Here's some code that demonstrates the problem:
Public Sub cnntest()
Dim cnn As ADODB.Connection
Dim sql As String
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.Open "DSN=redacted;UID=redacted;PWD=redacted;"
sql = "SELECT ITEM FROM IC_ITM_MST WHERE ITEM = '1400-4'"
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseServer
rs.Open sql, cnn
For Each a In rs.Fields
Debug.Print a.Name
Next a
Debug.Print rs.EOF
rs.Close
cnn.Close
End Sub
When I run the above code, it prints the name of the field, so I know that it's connecting to the database and executing the query. However, when it tries to evaluate rs.EOF, it immediately crashes and throws up an error message saying "Microsoft Excel has stopped working." It also does this when I mouse over that part of the code. The exact same code runs fine when I try it on Excel 2010 on Windows Server 2008.
Any idea why it works on the old version of Excel but not the new one? Any ideas on how to fix it?
Four months later, I finally found the answer. I used the Windows event viewer to look at the error logs for the crashes, which said
"Faulting application name: EXCEL.EXE, version 16.0.4266.1001, time
stamp: 0x55ba1551
Faulting module name: BBjODBC.dll, version 14.1.1.0, time stamp: 0x5400df87
Exception code: 0xc0000005
This confirmed that the problem was with the BBj driver. It turns out that the person responsible for updating that driver had updated it on all of the server's hard drives except for the C drive, which was the one that Excel decided to use. As a result, we were stuck using a five year old version of the driver even though our tech people claimed everything was up to date. We're currently waiting for the driver to be updated, so hopefully that will fix the issue.

ODBC Driver has become erratic when making connection and processing SQL query

I have an Excel Macro Workbook (binary extension) that suddenly has developed 2 issues occasionally (sometimes it runs fine).
#1 Issue - Occasionally there is an error on Line 5
It appears the connection does not open. We get the error:
Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x7f8 Thread 0x1174 DBC
#2 Issue - Occasionally there is an error on Line 7
It appears the SQL can not run. It indicates the Worksheet tab can not be found even though it does exist. Note for this error we have no issue with Line 5 (Open Connection). The error that displays is:
[Microsoft][ODBC Excel Driver] The microsoft jet database engine could not find the object 'Worksheet Name'. Make sure the object exists...
For Issue #2 once we close the error dialog box and THE MACRO GETS DELETED !!!
Notes
The code module has not been changed in years Some days we get no errors/issues
This issue occurs for multiple Excel workbooks run by multiple people that run different VBA code blocks. However 1 of the code blocks is the same across all these macros which is the code snippet above.
The source data has not changed in years in terms of formatting or volume.
All these workbooks are on a Network server.
We are on Windows7/Excel 2010/ODBC Excel Driver (xls xlsx xlsm xlsb)
14.00.7180.5000
Code Snippet
1-Set adoConn = Nothing
2-Set adoRS = Nothing
3-Application.EnableCancelKey = xldisabled
4-strConn = "Driver={Microsoft Excel Driver (*.xls,*.xlsx,*.xlsm,*.xlsb)};DriverId=1046;Dbq=" & strFileName & ";IMEX=1;"
5-Set adoConn = New ADODB.Connection: adoConn.Open strConn
6-Application.EnableCancelKey = xlInterrupt
7-Set adoRS = New ADODB.Recordset:adoRS.Open Source:=strSQL,ActiveConnection:=adoConn
I'm curious as to why you're using ODBC to connect Excel to another Excel file, as opposed as to linking the data directly.
Intermittent connection problems point to a network issue. I would suggest removing and re-creating the ODBC connection, but I'd first want to confirm the value of strFileName as referred to in the connection string. Is it an actual server on your internal network, or an external source? (ie, is it a UNC path?)
An intermittent Unable to open registry key error likely sounds worse than it is; when having connection problems, Windows & Excel will easily get confused as to what the real problem is.
It sounds like your setup has been in place, possibly un-maintained, for a long time. When is the last time the client and server were rebooted? (Should be nightly.) Defrag, disk cleanup, etc?
As for the issue of the macro "getting deleted" when you close an error dialog, I'd need to see proof of that. I think you're misunderstanding something, unless you're re-writing the macro from scratch each time this happens..

"Unspecified error" while opening an ADODB connection

I am facing "Unspecified error" in only one PC of my users.
Run-time error '-2147467259 (80004005)':
Unspecified error
I am running the below VBA code to open a connection to Access database located in network shared drive. But the code throws the error whenever it is trying to run the .Open statement.
I thought it is a driver issue and installed Access 2007 Database engine in the user's PC and replaced Provider with "Microsoft.ACE.OLEDB.12.0" but it doesn't work.
Code:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim retVal As Boolean
Dim strSQL As String
retVal = False
On Error GoTo CatchError
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Properties("Jet OLEDB:Database Password") = Initialize.GetDBPwd 'returns pass
.Open Initialize.GetDbConnectionString 'returns the network DB path
End With
I have the same issue while making an ADODB connection from a local Excel file to another local Excel file.
The only way how I solve it is re-opening the main Excel file from which I do the connection. Nothing else done, and the function works again.
My connection function:
Sub SetConReadOnly(ByRef con1 As Object, ByRef rst1 As Object, sFile As String)
If con1 Is Nothing Then Set con1 = CreateObject("ADODB.Connection")
If rst1 Is Nothing Then Set rst1 = CreateObject("ADODB.Recordset")
con1.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=No;IMEX=1;"""
End Sub
(I use Office 2013 32-bit, Windows 7 64-bit)
What is the version of your Excel?
I had that error, and the solution was changing the provider. Try changing to this:
On Error GoTo CatchError
Set cn = New ADODB.Connection
With cn
.provider = "Microsoft.Mashup.OleDb.1"
.Properties("Jet OLEDB:Database Password") = Initialize.GetDBPwd 'returns pass
.Open Initialize.GetDbConnectionString 'returns the network DB path
End With
Still haven't found any solution to this issue but it seem the issue is limited to only one user.
I wrote some test macros, in the same file which has the original macros, that open DB connection to local DB file and remote DB file. The test is successful but for some reason that one particular macro still throws that "Unspecified Error" in that specific users machine.
We concluded it is most likely due to a office got corrupted. We will repair the office and hopefully that should fix the issue. Will let you know if this works.
Thanks.
I have faced this issue and identified that this issue is specific to a Win7 64 Bit with a 32 Bit Office Installation. The solution I accidentally came across was that If I saved the file manually and rerun the code, it worked seamlessly post that. On trying to incorporate a save in the error handler and calling in the main function again did not work. However saving the file through Application.SendKeys "^s" and then running the file through another thread could replicate the outcome of the manual save.
On further investigation, I identified that the error was because of certain columns in the source being added at run-time before the query and it seems the sql engine queries from a different internal raw source which is not updated with the changes unless the save happens and that was the reason for error.
I got this error while using same variables in two different modules. It went away when I changed the variable names. It is strange but it worked!! Hope that solves your problem. Thanks

loading csv "Could not find installable ISAM"

Im building a program in Excel VBA to automate a process and I require data stored in a csv file to be imported. So, I'm trying to use a query table to import specific columns in a csv file.
Im using ADO to interface with the csv file using the Jet Provider OLE DB. In the connection string I have specified the provider, data source, and extended properties. Im using windows xp and office 2003, so my Excel version is 8.0. I specified the provider as Microsoft.Jet.OLEDB.4.0. My code is pasted below. When the code executes I get the error "Could not find installable ISAM" at the last line that I included in the below code. I cant find anything wrong with the syntax so I was wondering if this error could be because I dont have the correct version of Jet installed? Please see code below. Thanks
Sub Excel_QueryTable()
Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String
Dim qt As QueryTable
ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\testfile.csv;" & _
"Extended Properties=Excel 8.0;HDR=Yes; FMT=Delimited; IMEX=1"","
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open
Try this:
ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\directory\where\csv\file\is\;" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
I don't think you want to use the "Excel 8.0" portion, but you aren't actually connecting to an Excel worksheet; you're connecting to a text file. Also, you had extra spaces, and connection strings are REALLY picky about those, so I've deleted them.
Note that you can set the delimiter here:
HKLM\SOFTWARE\Microsoft\Jet\4.0\Engines\Text\Format
Mine is currently CSVDelimited; other options are TabDelimited and Delimited(;)
I found this info at: http://www.connectionstrings.com/textfile
-- EDIT --
Instead of pointing to a specific .csv file, you actually point the data source to a target directory. Note my changes above, in the connection string: the filename has been removed, and the path now ends in a \.
In order to use this type of data source, you actually need to teach the driver how the file is laid out. You do this through the use of a schema.ini file.
You can create the .ini file one of two ways:
Manually edit the file by hand, in notepad, using the above link to provide usage.
Use the tool built into the ODBC Data Source Admin.
In order to use the tool, you need to actually go through the steps of creating a data source. You don't actually need the data source, but as far as I can tell, it's the only way to get to the create schema.ini creation tool.
To get there:
Go to the ODBC control panel.
Add a new DSN, type: Microsoft Text Driver (*.txt, *.csv), click Finish
On "ODBC Text Setup", uncheck Use Current Directory and select the directory where your file lives.
Click on the options button, and click on the Define Format button.
Click on the file that you want to work with, and click "Guess" to get you started, then refine the data types as necessary.
When done, click OK, and you should see a schema.ini file in the directory where your .csv file is. Open it in notepad, and make sure it looks right.
The above connection string should now work correctly, using ONLY the directory where your csv lives, not the full path to the .csv.

Resources