Modify an embedded Connection String in microsoft excel macro

前端 未结 6 664
我在风中等你
我在风中等你 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:51

    I think you are so close to achieve what you want.

    I was able to change for ODBCConnection. Sorry that I couldn't setup OLEDBConnection to test, you can change occurrences of ODBCConnection to OLEDBConnection in your case.

    Try add this 2 subs with modification, and throw in what you need to replace in the CommandText and Connection String. Note I put .Refresh to update the connection, you may not need until actual data refresh is needed.

    You can change other fields using the same idea of breaking things up then Join it later:

    Private Sub ChangeConnectionString(sInitialCatalog As String, sDataSource As String)
        Dim sCon As String, oTmp As Variant, i As Long
        With ThisWorkbook.Connections("Job_Cost_Code_Transaction_Summary").ODBCConnection
            sCon = .Connection
            oTmp = Split(sCon, ";")
            For i = 0 To UBound(oTmp) - 1
                ' Look for Initial Catalog
                If InStr(1, oTmp(i), "Initial Catalog", vbTextCompare) = 1 Then
                    oTmp(i) = "Initial Catalog=" & sInitialCatalog
                ' Look for Data Source
                ElseIf InStr(1, oTmp(i), "Data Source", vbTextCompare) = 1 Then
                    oTmp(i) = "Data Source=" & sDataSource
                End If
            Next
            sCon = Join(oTmp, ";")
            .Connection = sCon
            .Refresh
        End With
    End Sub
    
    Private Sub ChangeCommanText(sCMD As String)
        With ThisWorkbook.Connections("Job_Cost_Code_Transaction_Summary").ODBCConnection
            .CommandText = sCMD
            .Refresh
        End With
    End Sub
    

提交回复
热议问题