如何命名QueryTable使用的连接

时间:2015-12-16 16:52:48

标签: excel excel-vba vba

我目前的代码:

ConnectionName = "testCon"
With ActiveSheet.QueryTables.Add(Connection:= _
    "URL;http://test/test?values=[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]~[]&format=csv" _
    , Destination:=Range("$D$1"))
    .Name = ConnectionName
End With

这会导致创建一个新的连接,名为" Connection",如果该过程重复,那么#34; Connection1"创建,然后" Connection2"等等。有没有办法命名连接?

<。> .Name参数似乎是指数据范围名称,而不是连接名称。

2 个答案:

答案 0 :(得分:2)

最后我没有找到直接命名新查询表连接的方法,因此我必须编写一个宏来查找连接列表中的新名称,然后重命名它。

Sub NewQueryTable(ConnectionName As String)
    OriginalConnections = ConnectionList()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://myconnection&format=csv" _
        , Destination:=Range("$D$1"))
        .Name = ConnectionName
    End With


' Looking for the newly created Connection to rename it
'''''''''''''''''''''''''''''''''''''''''''''''''''''
    UpdatedConnections = ConnectionList()
    Dim NewConnectionName As String
    Dim CheckedString As String


    For Each conn In UpdatedConnections
        CheckedString = conn
        If Not (IsInArray(CheckedString, OriginalConnections)) Then
            NewConnectionName = CheckedString
        End If
    Next conn

    With ActiveWorkbook.Connections(NewConnectionName)
            .Name = ConnectionName
            .Description = ""
    End With


End Sub


Function ConnectionList() As Variant

    Dim NumOfConnections As Integer
    Dim Counter As Integer


    NumOfConnections = 0
    Counter = 1


    Dim conn As WorkbookConnection
    For Each conn In ActiveWorkbook.Connections
        NumOfConnections = NumOfConnections + 1
    Next conn


    Dim ConnectionNames() As String, size As Integer, i As Integer
    size = NumOfConnections
    ReDim ConnectionNames(size)

    For Each conn In ActiveWorkbook.Connections
        ConnectionNames(Counter) = conn.Name
        Counter = Counter + 1
    Next conn

    ConnectionList = ConnectionNames


End Function

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean

        IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)

End Function

答案 1 :(得分:0)

这仍然是Google的头等大事,所以我想我会回答。您使用WorkbookConnection对象的QueryTable属性:

Dim oQT As QueryTable

Set oQT = ActiveSheet.ListObjects(1).QueryTable

'Rename the connection
With oQT.WorkbookConnection
    .Name = "NewConnectionName"
    .Description = "New Connection Description"
End With

'Delete the connection
oQT.WorkbookConnection.Delete