我正在与一个必须识别excel文件中某些变量的人合作。目前,和我一起工作的人有很多文件夹和子文件夹,其中有Excel文档。他使用一个VBA代码,该代码在文件夹中查找子文件夹,然后返回路径,然后创建到子文件夹的超链接(这不是下面的VBA代码的一部分),并查看所有excel文件,不管主文件夹中的子文件夹的级别如何。
下面是代码:
Sub GetFolders()
Dim path As String
Dim folder As String
Dim row As Integer
path = "your directory here"
folder = Dir(path, vbDirectory)
row = 1
Do While folder <> ""
If (GetAttr(path & folder) And vbDirectory) = vbDirectory Then
Cells(row, 1) = path & folder
row = row + 1
End If
folder = Dir()
Loop
End Sub
这很好,但我知道一定有更好的方法。如何操作此代码以返回在文件夹中找到的任何excel文件的列标题,或者返回文件夹中包含的子文件夹中的列标题( B)。我希望将这些文件返回到excel电子表格中,这样就不需要打开excel文档,而只需要打开这个文档,然后我们就可以识别出任何需要进一步调查的excel电子表格,而忽略了其余的。
发布于 2016-08-25 01:28:25
您可以使用ADO查询它们(根据需要调整连接字符串):
'Requires reference to Microsoft ActiveX Data Objects #.# Library
Private Function GetHeaders(filepath As String) As String()
Dim output() As String
Dim ado As New ADODB.Connection
output = Split(vbNullString)
With ado
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & filepath & "';" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;"";"
With .OpenSchema(adSchemaTables)
Dim table As String
Dim columns As ADODB.Recordset
Do While Not .EOF
table = .Fields("TABLE_NAME")
Set columns = ado.OpenSchema(adSchemaColumns, Array(Empty, Empty, table))
With columns
Do While Not .EOF
ReDim Preserve output(UBound(output) + 1)
output(UBound(output)) = table & .Fields("COLUMN_NAME")
.MoveNext
Loop
End With
.MoveNext
Loop
End With
End With
GetHeaders = output
End Function
然后对您找到的每个文件都这样调用它:
Sub Example()
Dim headers() As String
Dim i As Long
headers = GetHeaders("C:\Foo\Bar.xlsx")
For i = LBound(headers) To UBound(headers)
Debug.Print headers(i)
Next i
End Sub
请注意,这假设您不知道工作表名,并且需要获取的所有的头。输出数组中的字符串将以Sheet$Field
的形式出现,但可以根据需要进行调整。
发布于 2020-11-27 18:10:05
由于ADODB中的限制,col头中的单元格仅限于255个字符。
https://stackoverflow.com/questions/39132792
复制相似问题