我相信在这之后你会爱上VBA。
对于您想要实现的目标,将有4个部分(子部分):
-
列出所有子项
联系
和
命令文本
工作簿(如果有)
-
Sub获取文件夹中所有Excel文件的名称
-
要在上面递归到每个子文件夹的子文件夹
-
要在上面发起的主要Sub
考虑我的代码如下:
Private Const FILE_FILTER = "*.xl*"
Private Const sRootFDR = "C:\Users\lchua\" ' Root Folder
Private oFSO As Object ' For FileSystemObject
Private oRng As Range, N As Long ' Range object and Counter
Sub Main()
Application.ScreenUpdating = False
Set oFSO = CreateObject("Scripting.FileSystemObject")
N = 0
With ThisWorkbook.Worksheets("Sheet1")
.UsedRange.ClearContents ' Remove previous contents
.Range("A1:D1").Value = Array("Filename", "Connections", "Connection String", "Command Text")
Set oRng = .Range("A2") ' Initial Cell to start storing results
End With
ListFolder sRootFDR
Application.ScreenUpdating = True
Set oRng = Nothing
Set oFSO = Nothing
MsgBox N & " Excel files has been checked for connections."
End Sub
Private Sub ListFolder(ByVal sFDR As String)
Dim oFDR As Object
' List the files of this Directory
ListFiles sFDR, FILE_FILTER
' Recurse into each Sub Folder
For Each oFDR In oFSO.GetFolder(sFDR).SubFolders
ListFolder oFDR.Path & "\" ' Need '\' to ensure the file filter works
Next
End Sub
Private Sub ListFiles(ByVal sFDR As String, ByVal sFilter As String)
Dim sItem As String
sItem = Dir(sFDR & sFilter)
Do Until sItem = ""
N = N + 1 ' Increment Counter
oRng.Value = sFDR & sItem
CheckFileConnections oRng.Value ' Call Sub to Check the Connection settings
Set oRng = oRng.Offset(1) ' Move Range object to next cell below
sItem = Dir
Loop
End Sub
Private Sub CheckFileConnections(ByVal sFile As String)
Dim oWB As Workbook, oConn As WorkbookConnection
Dim sConn As String, sCMD As String
Application.StatusBar = "Opening workbook: " & sFile
Set oWB = Workbooks.Open(Filename:=sFile, ReadOnly:=True)
With oWB
oRng.Offset(0, 1).Value = .Connections.Count ' 1 column to right (B)
For Each oConn In .Connections
If Len(sConn) > 0 Then sConn = sConn & vbLf
If Len(sCMD) > 0 Then sCMD = sCMD & vbLf
sConn = sConn & oConn.ODBCConnection.Connection
sCMD = sCMD & oConn.ODBCConnection.CommandText
Next
oRng.Offset(0, 2).Value = sConn ' 2 columns to right (C)
oRng.Offset(0, 3).Value = sCMD ' 3 columns to right (D)
End With
oWB.Close False ' Close without saving
Set oWB = Nothing
Application.StatusBar = False
End Sub
我的测试文件夹不包含任何具有连接的工作簿,因此输出为:
您应该根据工作表更改存储这些信息的位置。你可能想评论一下
MsgBox
。希望它不会在连接相关时出错。