I would like to run SQL queries on tables all contained within a single Excel workbook. My VBA code uses ADODB to run these SQL queries.
Opening connection fails when the workbook is saved in OneDrive, but works when workbook is saved to a local drive.
How can I run SQL on tables within a single excel workbook, while saved on OneDrive?
The code works when the book is saved locally but not on OneDrive. The only change is the file path which looks fairly different in each case:
OneDrivePathExample = "https://d.docs.live.net/....xlsb"
LocalPathExample = "C:\My Documents\....xlsb"
I've experimented with a few things around the file path in the connection string but, unsurprisingly, they didn't work:
Original
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=https://d.docs.live.net/.../Documents/Financial Tracker.xlsb;Extended Properties="Excel 12.0;HDR=Yes;IMEX=1";
Replacing "/" with "\"
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=https:\\d.docs.live.net\...\Documents\Financial Tracker.xlsb;Extended Properties="Excel 12.0;HDR=Yes;IMEX=1";`
Adding square brackets around path
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[https://d.docs.live.net/.../Documents/Financial Tracker.xlsb];Extended Properties="Excel 12.0;HDR=Yes;IMEX=1";
Adding quotes around path
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="https://d.docs.live.net/.../Documents/Financial Tracker.xlsb";Extended Properties="Excel 12.0;HDR=Yes;IMEX=1";
I realize that I can avoid this by saving it locally when running this code, and then save it back to OneDrive afterwards but I would like to avoid this if possible.
I also realize that I can write VBA code that does what I'm trying to do with SQL, however I did that originally but switched to the SQL method because SQL was way faster.
Here's my code:
Function OpenRST(strSQL As String) As ADODB.Recordset
''Returns an open recordset object
Dim cn As ADODB.Connection
Dim strProvider As String, strExtendedProperties As String
Dim strFile As String, strCon As String
strFile = ThisWorkbook.FullName
strProvider = "Microsoft.ACE.OLEDB.12.0"
strExtendedProperties = """Excel 12.0;HDR=Yes;IMEX=1"";"
strCon = "Provider=" & strProvider & _
";Data Source=" & strFile & _
";Extended Properties=" & strExtendedProperties
Set cn = CreateObject("ADODB.Connection")
Set OpenRST = CreateObject("ADODB.Recordset")
cn.Open strCon ''This is where it fails
OpenRST.Open strSQL, cn
End Function
On the cn.Open strCon
line, the following error appears:
Run-time error '-2147467259 (80004005)';
Method 'Open' of object '_Connection' failed
Thanks!