Question : Changing the source for a query

Hi,

I recently created an excel file that contains about a hundred queries linked to a Microsoft Access file. Both the excel file and access file were on my desktop. I now how to move the two files from my desktop to another server. How do I change the source for the queries in my excel file to account for the change. The names of the files will still be the same, and both of the files will be in the same folder, but they will be on a different drive. To create the queries I just went to Data>Import External Data>New Database Query and then for the data source I selected Microsoft Access Database.

Thanks, Greg.

Answer : Changing the source for a query

Try the following code (back up your file first)
This only works where the old/new files are mdb files, and all queries refer to the same source

Copy the macro to a new module
Create a new worksheet in your file
In A1, put the old file, with full path, but without the file extension (eg: C:\yourfolder\yourfile)
In A2, put the new file, full path no extension (eg: S:\newfolder\newfile)

Run the macro
If the new database has a password it will be requested.
All queries will be updated and refreshed

Method based on code at http://www.dicks-clicks.com/excel/ExternalData5.htm
Modified to make it operational.

Regards
Mike
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
Sub ChangeConn()
 
    Dim wbBook As Workbook
    Dim qt As QueryTable
    Dim Wsh As Worksheet
    Dim OldLoc As String, OldPath As String
    Dim NewLoc As String, NewPath As String
    Dim LastSlash As Long
    Const Ext As String = ".mdb"
     
    Set wbBook = ActiveWorkbook
    Set Wsh = wbBook.Worksheets(1)
    
    Range("a1").Select
    OldLoc = Selection.Value
    Range("a2").Select
    NewLoc = Selection.Value
    
     LastSlash = InStrRev(OldLoc, "\", , vbTextCompare)
     OldPath = Left(OldLoc, LastSlash - 1)
 
     LastSlash = InStrRev(NewLoc, "\", , vbTextCompare)
     NewPath = Left(NewLoc, LastSlash - 1)
 
     For Each Wsh In wbBook.Worksheets
          For Each qt In Wsh.QueryTables
               qt.Connection = Replace(qt.Connection, OldLoc & Ext, NewLoc & Ext)
               qt.CommandText = Replace(qt.CommandText, OldLoc, NewLoc)
               qt.Connection = Replace(qt.Connection, OldPath, NewPath)
               qt.Refresh
          Next qt
     Next Wsh
 
End Sub
Random Solutions  
 
programming4us programming4us