Excel Data Connection Locks Access DB, Prevents Second Connection's Refresh
I was faced with another issue regarding data connections, and the solution for it actually ended up fixing this long-standing issue as well!
My guess is that the secret lies in "MaintainConnection = False":
Dim i As Integer
Dim awc As WorkbookConnection
Dim c As OLEDBConnection
For i = 0 to ActiveWorkbook.Connections.Count
Set awc = ActiveWorkbook.Connections.Item(i)
Set c = awc.OLEDBConnection
c.EnableRefresh = True
c.BackgroundQuery = False
c.Reconnect
c.Refresh
c.MaintainConnection = False
Next i
Your answer really helped me. I had the same problem, but with Excel files: an Excel file accessing another Excel (when opening) with Microsoft.ACE.OLEDB.12.0 and this datasource file getting locked (in use).
So, I removed the "refresh data when opening the file", and I replace this with your VBA code in Workbook_Open event. But I improved a little your code, because I was getting errors, since I have another ODBC connection (not OLEBD) in my workbook, I had to add this IF. Now everything works well.
Private Sub Workbook_Open()
Dim i As Integer
Dim awc As WorkbookConnection
For i = 1 To ActiveWorkbook.Connections.Count
Set awc = ActiveWorkbook.Connections.Item(i)
If awc.Type = xlConnectionTypeOLEDB Then
With awc.OLEDBConnection
.EnableRefresh = True
.BackgroundQuery = False
.Reconnect
.Refresh
.MaintainConnection = False
End With
ElseIf awc.Type = xlConnectionTypeODBC Then
With awc.ODBCConnection
.EnableRefresh = True
.BackgroundQuery = False
.Refresh
End With
End If
Next i
End Sub