I use ADO to get data from an excel file. For testing purposes I created two files: Data.xlsx with some data and Adotest.xlsm with this piece of code:
Case 1a: run the code and don't be surprised.
Case 1b: step through the code but stop after the connection.open. Now try to open Data.xlsm from Excel or Explorer. Again no surprises (although... strange message isn't it?).
Case 2a: now first open Data.xlsx, then run the code. Hey, isn't the file locked? And hey, some headers!
Case 2b: again run to after .Open, switch to Data.xlsx, change some data, save, and switch back to Adotest. Continue stepping.
Case 3a: same as 2a but open in a new excel instance. Hey, at the .Open ADO opens Data.xlsx Read-Only!
Case 3b: you know...
I am very very much surprised that Ado doesn't throw an error when trying to open a locked file. Am i missing something?
My current work around: before connecting i use vba-open to test if the file is in use. Any other suggestions?
Thanks!
- Frans
(Windows Vista Ultimate, Office Ultimate 2007. I tried ADO 2.7 and ADO 6.0, same results.)
Code:
Dim sFullName As String
sFullName = ThisWorkbook.Path & "\Data.xlsx"
' setup and open connection
Dim sConnect As String
sConnect = ""
sConnect = sConnect & "Provider=Microsoft.ACE.OLEDB.12.0;"
sConnect = sConnect & "Data Source=" & sFullName & ";"
sConnect = sConnect & "Mode=Share Exclusive;" ' 12
sConnect = sConnect & "Extended Properties=""Excel 12.0;HDR=YES;"""
Dim adoConnection As ADODB.Connection
Set adoConnection = New ADODB.Connection
adoConnection.ConnectionString = sConnect
adoConnection.Open
' get data
Dim rsData As ADODB.Recordset, sSql As String
Set rsData = New ADODB.Recordset
sSql = "SELECT * FROM [Sheet1$]"
rsData.Open sSql, adoConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
Sheet1.Cells.ClearContents
Sheet1.Range("B2").CopyFromRecordset rsData
rsData.Close
' close
adoConnection.Close
Set adoConnection = Nothing
Case 1b: step through the code but stop after the connection.open. Now try to open Data.xlsm from Excel or Explorer. Again no surprises (although... strange message isn't it?).
Case 2a: now first open Data.xlsx, then run the code. Hey, isn't the file locked? And hey, some headers!
Case 2b: again run to after .Open, switch to Data.xlsx, change some data, save, and switch back to Adotest. Continue stepping.
Case 3a: same as 2a but open in a new excel instance. Hey, at the .Open ADO opens Data.xlsx Read-Only!
Case 3b: you know...
I am very very much surprised that Ado doesn't throw an error when trying to open a locked file. Am i missing something?
My current work around: before connecting i use vba-open to test if the file is in use. Any other suggestions?
Thanks!
- Frans
(Windows Vista Ultimate, Office Ultimate 2007. I tried ADO 2.7 and ADO 6.0, same results.)