Modify an embedded Connection String in microsoft excel macro

前端 未结 6 665
我在风中等你
我在风中等你 2020-12-14 19:01

I have an Excel document that has a macro which when run will modify a CommandText of that connection to pass in parameters from the Excel spreadsheet, like so:

6条回答
  •  甜味超标
    2020-12-14 19:53

    You could use a function that takes the OLEDBConnection and the parameters to be updated as inputs, and returns the new connection string. It's similar to Jzz's answer but allows some flexibility without having to edit the connection string within the VBA code each time you want to change it - at worst you'd have to add new parameters to the functions.

    Function NewConnectionString(conTarget As OLEDBConnection, strCatalog As String, strDataSource As String) As String
    
        NewConnectionString = conTarget.Connection
        NewConnectionString = ReplaceParameter("Initial Catalog", strCatalog)
        NewConnectionString = ReplaceParameter("Data Source", strDataSource)
    
    End Function
    
    Function ReplaceParameter(strConnection As String, strParamName As String, strParamValue As String) As String
    
        'Find the start and end points of the parameter
        Dim intParamStart As Integer
        Dim intParamEnd As Integer
        intParamStart = InStr(1, strConnection, strParamName & "=")
        intParamEnd = InStr(intParamStart + 1, strConnection, ";")
    
    
        'Replace the parameter value
        Dim strConStart As String
        Dim strConEnd As String
        strConStart = Left(strConnection, intParamStart + Len(strParamName & "=") - 1)
        strConEnd = Right(strConnection, Len(strConnection) - intParamEnd + 1)
    
        ReplaceParameter = strConStart & strParamValue & strConEnd
    
    End Function
    

    Note that I have modified this from existing code that I have used for a particular application, so it's partly tested and might need some tweaking before it totally meets your needs.

    Note as well that it'll need some kind of calling code as well, which would be (assuming that the new catalog and data source are stored in worksheet cells):

    Sub UpdateConnection(strConnection As String, rngNewCatalog As Range, rngNewSource As Range)
    
        Dim conTarget As OLEDBConnection
        Set conTarget = ThisWorkbook.Connections.OLEDBConnection(strConnection)
    
        conTarget.Connection = NewConnectionString(conTarget, rngNewCatalog.Value, rngNewSource.Value)
        conTarget.Refresh
    
    End Sub
    

提交回复
热议问题