无法使用VBA从Access to Excel中提取带有数据的标头,

时间:2018-10-12 13:57:38

标签: excel vba ms-access outlook

如何修改查询,以便还可以提取标题?

Sub AccessToExcel()

    ControlFile = ActiveWorkbook.Name

    Dim myrange As Range
    Set myrange = ActiveWorkbook.Sheets("Control").Range("C9")

    Dim i As Integer
    i = 1

    Do While Len(myrange.Offset(i, 0)) > 0

        Dim terr_filter As String
        terr_filter = myrange.Offset(i, 1).Value
        Dim terr_name As String
        terr_name = myrange.Offset(i, 0).Value
        Dim file_path As String
        file_path = myrange.Offset(i, 3).Value
        Dim file_name As String
        file_name = myrange.Offset(i, 2).Value

        Dim j As Long, sPath_Access_DB As String
        Dim oDAO As DAO.DBEngine, oDB As DAO.Database, oRS As DAO.Recordset
        Dim strPath As String

        sPath_Access_DB = Range("rng_Ctrl_Path").Value

        'Exporting Component Summary to Access
        If sPath_Access_DB = "" Then Exit Sub

        Set oDAO = New DAO.DBEngine
        Set oDB = oDAO.OpenDatabase(sPath_Access_DB, dbOpenDynaset)
        Set oRS = oDB.OpenRecordset(terr_name)

        Sheets.Add After:=ActiveSheet

        Range("B2").CopyFromRecordset oRS

        ActiveSheet.Name = terr_filter

        oDB.Close

        i = i + 1
    Loop
End Sub

1 个答案:

答案 0 :(得分:0)

您需要循环并自己提取它们:

For j = 1 to oRS.Fields.Count
   Cells(1, j + 1).Value = oRS.Fields(j - 1).Name
Next