Excel Data Connection Locks Access DB, Prevents Second Connection's Refresh

后端 未结 4 1163
囚心锁ツ
囚心锁ツ 2021-02-09 17:35

I have two data connections to different queries in the same Access DB. The second one always fails (regardless of which I run first).

When I look at the database, I no

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 17:59

    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
    

提交回复
热议问题