I am delving into the world of VBA data connections, and would appreciate some assistance. The code below is what I have so far, but there are a couple of oddities I can't figure out.
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = "C:\USERS\NAME\DOCUMENTS\VBA Work\Data Source.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLQry = "SELECT * From [Sheet1$]"
mrs.Open sSQLQry, Conn
Sheet3.Range("A1").CopyFromRecordset mrs
mrs.Close
Conn.Close
End Sub
This code works, however:
- The data pulled in doesn't include Row1 of the dataset (so the headers aren't pulled in)
- If the source workbook 'Data Source.xlsx' is open. The code will cause the workbook to open again but in read-only mode. Can this be avoided?
- Can the connection string be edited so that the source file is never locked out? ie. queried in Read-Only mode other users can open it whilst the query is being completed?
Any help is appreciated Thanks Caleeco
Fieldscollection.Mode=read;in the connection string?Conn.Open sconnect, then try to open the source fileData Source.xlsxi get theFile is Locked by Another Userwarning message. This is undesirable as I have many people on the network that need Write access to that source file. Not too concerned about a second instance being opened asRead-onlyif someone ALREADY has the file locked out as I can close it with VBA after.sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';Mode=Read;ReadOnly=True;"but still get the same problem of locking out this file while the query is executed.Set mrs = Nothingand thenSet Conn = Nothingafter you close both, that should put the final nail in these objects' coffins. TBH the best solution is to put that data where it belongs: in a database. Even MS-Access would do.