我需要更新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
任何帮助都会很棒。感谢。
答案 0 :(得分: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
答案 1 :(得分: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
感谢大家的帮助。