Programmatically rename tables in Access queries

前端 未结 2 567
囚心锁ツ
囚心锁ツ 2021-01-24 20:01

I have an access 2003 database file with hundreds of queries. I would like to rename all tables referenced from within my queries based on a condition

If tableNa         


        
2条回答
  •  死守一世寂寞
    2021-01-24 20:06

    I have a quick & dirty VBA sub which does what I think you want. (Can you translate it to one of your preferred languages?) You could try it with a copy of your database. (DO NOT try it with the only copy of a database you want to keep!)

    To substitute "tblBar" for "tblFoo" in your queries, you can run it from the VBE Immediate Window (from Access, Ctrl+g will get you there) like this:

    call swapTblNamesInQueryDefs("tblFoo", "tblBar")
    

    To actually save the changed query definitions, call it like so:

    call swapTblNamesInQueryDefs("tblFoo", "tblBar", "savechanges")
    

    The code:

    Public Sub swapTblNamesInQueryDefs(ByVal pstrFind As String, _
    ByVal pstrReplace As String, _
    Optional ByVal pstrMode As String = "DisplayOnly")
    
    Dim qd As QueryDef
    Dim re As Object
    Dim strSql As String
    
    Set re = CreateObject("vbscript.regexp")
    re.Global = True
    re.IgnoreCase = True
    
    re.Pattern = "\b" & pstrFind & "\b"
    
    For Each qd In CurrentDb.QueryDefs
        If Left$(qd.Name, 1) <> "~" Then
            Debug.Print qd.Name
            Debug.Print "Before: " & qd.SQL
            strSql = re.Replace(qd.SQL, pstrReplace)
            Debug.Print "After: " & strSql
            'only save the modified SQL statement if called
            'with SaveChanges parameter
            'If pstrMode = "SaveChanges" Then
            If StrComp(pstrMode, "SaveChanges", vbTextCompare) = 0 Then
                qd.SQL = strSql
            End If
            Debug.Print String(20, "-")
        End If
    Next qd
    Set re = Nothing
    Set qd = Nothing
    End Sub
    

    Edit: Changed evaluation of pstrMode to guarantee case insensitive comparison (in case module includes "Option Compare Binary").

提交回复
热议问题