Using ADODB to access opened xls file

雨燕双飞 提交于 2019-12-18 06:49:11

问题


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 :)


回答1:


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.




回答2:


Your Excel version is 2007 or later?

if is use Microsoft.ACE.OLEDB.12.0 at provider and your problem is solved.

[]´s




回答3:


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



来源:https://stackoverflow.com/questions/8985580/using-adodb-to-access-opened-xls-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!