使用VBA获取Excel选项卡名称并复制到Access表

时间:2014-12-20 17:50:44

标签: vba excel-vba access-vba excel

我需要将Excel文件中的标签名称保存到Access表中供以后使用。我可以使用Debug.Print将它们打印到Immediate窗口,或者使用Print#发送到.txt文件,但是无法弄清楚如何将它们放到数据库中的表中。提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您的问题已部分回答(Using Excel VBA to export data to MS Access table)。为了传输数据(与您的案例相关,Excel选项卡名称存储,例如,在列中" A")从Excel到Access Table,请使用以下代码段:

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="yourExcelTable", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            ' your data column, for example A1
            Range:="Sheets1$A1:A10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

希望这会有所帮助。

答案 1 :(得分:0)

我不确定这是不是你在说什么。假设您正在尝试创建一个包含工作簿中“选项卡”的NAMES的表,我正在编写此代码。然后你可以使用这个新表并将其导入ACCESS。如果我误解,只需评论。

Private Sub CreateSheetFromNames()

Dim ws As Worksheet
Dim lRow As Long
Dim sheet As String

'---SET UP WORKSHEET TO STORE ALL THE TAB NAMES---'
    sheet = "Master"
    Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count))
    ws.Name = sheet

    'Format the Column Header and Font Properties
    ws.Cells(1, 1) = "Tab Name"
    With ws.Cells(1, 1).Font
        .Bold = True
    End With

    'Define Row for new sheet and loop through worksheets getting names
    lRow = 2

    For Each ws In Worksheets
        If ws.Name <> sheet Then
            Sheets(sheet).Cells(lRow, 1) = ws.Name
            lRow = lRow + 1
        End If
    Next ws

    'Widen the target column to account for widest entry
    With Sheets(sheet)
        Columns(1).AutoFit
        Columns(1).HorizontalAlignment = xlCenter
    End With

End Sub

RESULT