使用VBA从Excel文件中检索列标题

我正在和一些必须在excel文件中识别某些variables的人一起工作。 目前,我正在使用的人有大量的文件夹和子文件夹中有Excel文档。 他使用的VBA代码在一个文件夹中查找子文件夹,然后返回该path,然后创build超链接到子文件夹(这不是下面的VBA代码的一部分),并查看所有的Excel文件,不pipe主文件夹内的子文件夹的级别如何。

代码如下:

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文件的文件夹头,在文件夹中包含的子文件夹内findA)在一个文件夹内或B)。 我希望将这些数据返回到excel电子表格中,以便不需要打开100个excel文档,而只需要打开这个文档,然后我们就可以find需要进一步调查的excel电子表格,并忽略其余部分。

您可以使用ADO查询它们(根据需要调整连接string):

 '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 

然后像这样为每个find的文件调用它:

 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 

请注意,这假设你不知道表名,并需要为所有的表头。 输出数组中的string将以Sheet$Field的forms显示,但可以根据需要进行调整。