问题
I have a raft of Excel 2013 workbooks that I have to refine, each with multiple sheets and multiple data connections and I am looking for a quick way to list:
- connection name
- connection string
- location(s) where connections are used (sheet name or range would be useful)
I can see all this information in the connections dialogs but am having trouble tracking them down programmatically. I want to do this one file at a time so am not worried about running code across all the files, just something I can drop in a module as I start work on the file concerned. So far I have found this on this site:
Dim conn As WorkbookConnection
For Each conn In ActiveWorkbook.Connections
Debug.Print conn.Name
Next conn
but I can't find the location information to go alongside this. Any pointers would be very gratefully received.
Cheers
Kyle
回答1:
Expected output :
(Connection's Name): Sheet'sName|1st Cell of Range
Connection's ODBC Command Text
(Connection's Name): Sheet'sName|1st Cell of 1st Range // Sheet'sName|1st Cell of 2nd Range
Here you go :
Private Sub List_Connections_Ranges()
Dim wC As WorkbookConnection
Dim rG As Range
Dim TpStr As String
For Each wC In ActiveWorkbook.Connections
TpStr = "(" & wC.Name & ") found on : "
For Each rG In wC.Ranges
TpStr = TpStr & rG.Parent.Name & "|" & rG.Cells(1, 1).Address(0, 0) & " // "
Next rG
Debug.Print Left(TpStr, Len(TpStr) - 4)
Debug.Print wC.ODBCConnection.CommandText
Next wC
End Sub
回答2:
The code looks like ok to me. Can you try it like this to see whether you have connections at all:
Public Sub TestMePlease()
Dim conn As WorkbookConnection
If ActiveWorkbook.Connections.Count > 0 Then
For Each conn In ActiveWorkbook.Connections
Debug.Print conn.Name
Next conn
Else
Debug.Print "No connection found"
End If
End Sub
Edit: More information about connection is in the library. To see it, press ctrl + space like this:
Concerning the sheet name, it is here:
Debug.Print conn.Ranges.Item(1).Parent.Name
Concerning the connection string, Microsoft would not give you a possibility to access such information from VBA. If it is available it should be a giant security problem.
来源:https://stackoverflow.com/questions/42113354/find-locations-where-connections-are-used-excel-vba