4

我需要更新 excel 工作簿的 sql 连接的连接名称。这是我的尝试。我已经能够通过标准替换来修改连接字符串和命令文本。

Sub ConnectionString_modify()

Dim i As Long
Dim cnt As Long
Dim modtext As String
Dim modrange As String

'Grab nummber of workbook connections
cnt = ActiveWorkbook.Connections.Count

For i = 1 To cnt

    'Changes to Connection string --This works
    modtext = ActiveWorkbook.Connections.Item(i).OLEDBConnection.Connection
    modtext = VBA.Replace(modtext, "_FY2013", "_FY2014")
    ActiveWorkbook.Connections.Item(i).OLEDBConnection.Connection = modtext

    'Changes Connection Name
    modname = ActiveWorkbook.Connections.Item(i).Name
    modname = VBA.Replace(modname, "_FY2013", "_FY2014")
    ActiveWorkbook.Connections.Item(i).Name = modname 
 Next i

End sub

任何帮助都会很棒。谢谢。

4

2 回答 2

4

尝试这个:

Sub ConnectionString_modify()

Dim i As Long
Dim cnt As Long
Dim modtext As String
Dim modrange As String
Dim conn

'Grab nummber of workbook connections
cnt = ActiveWorkbook.Connections.Count

For i = cnt To 1 Step -1

    Set conn = ActiveWorkbook.Connections.Item(i)

    modtext = conn.OLEDBConnection.Connection
    modtext = VBA.Replace(modtext, "_FY2013", "_FY2014")
    conn.OLEDBConnection.Connection = modtext

    conn.Name = VBA.Replace(conn.Name, "_FY2013", "_FY2014")

Next i

End sub
于 2013-09-17T16:16:09.590 回答
0

显然,Excel 动态排序 Connection.Item() 数组。所以我的修改是将更新后的名称发送到数组的底部。之前:FY2013Conn1、FY2013Conn2、FY2013Conn3、FY2013Conn4 之后:FY2014Conn2、FY2014Conn3、FY2014Conn4、FY2014Conn1

这很难看到,因为我正在处理 50 多个连接。我发现有效的方法不是尝试遍历整个集合,而是只修改数组中的第一项。

'Connection Count
cnt = ActiveWorkbook.Connections.Count 

While cnt > 0
   'Always modify the first Item 
   Set conn = ActiveWorkbook.Connections.Item(1)

   'Mod code makes changes to Command Text
    modtext = conn.OLEDBConnection.Connection
    modtext = VBA.Replace(modtext, "_FY2013", "_FY2014")
    conn.OLEDBConnection.Connection = modtext

    'Changes Connection Name
    conn.Name = VBA.Replace(conn.Name, "_FY2013", "_FY2014")

    'Iterate through the cnt
     cnt = cnt - 1
  Wend

感谢大家的帮助。

于 2013-09-18T16:08:39.613 回答