Using VBA to retrieve Column Headers from Excel files

后端 未结 2 919
我寻月下人不归
我寻月下人不归 2020-12-10 09:50

I\'m working with someone who has to identify certain variables within excel files. Currently, the man I\'m working with has a great deal of folders and sub-folders that ha

2条回答
  •  情深已故
    2020-12-10 10:23

    You can query them with ADO (adjust the connection string as needed):

    '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
    

    Then call it like this for each file that you 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
    

    Note that this assumes you don't know the sheet names and need to get headers for all of them. The strings in the output array will be in the form of Sheet$Field, but that can be adjusted according to need.

提交回复
热议问题