Question

I can connect the excel file to itself as a datasource for MS Query to work. But as soon as I move the file around the query tries to find it from its previous location on the network and fails.
I just want it to try and query itself.
I tried removing the directory path from the connection string in the datasource but it just errored.

Is this even possible?
Or is there a better way?

Was it helpful?

Solution

Can you use VBA? If you do, you can place code in ThisWorkbook to update query string:

Sub UpdateQuery()
    'This is just an example. Query must be changed accordingly
    ThisWorkbook.Connections(1).ODBCConnection = "SELECT `Sheet1$`.a, `Sheet1$`.b FROM `" & ThisWorkbook.FullName & "`.`Sheet1$` `Sheet1$`"
End Sub

Private Sub Workbook_AfterSave(ByVal Success As Boolean)
    If Success Then UpdateQuery
End Sub

Private Sub Workbook_Open()
    UpdateQuery
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top