excel - 如何通过vba将一个包含多个工作表的excel文件导入到 Access 表中

标签 excel vba ms-access

我必须通过 vba 将一个包含多个工作表的 excel 文件导入到 Access 表中,但我下面列出的当前代码只会复制 excel 的第一个工作表记录并导入到 Access 表中,所有工作表都具有相同的格式和布局。如何使我的代码能够复制所有工作表的记录并导入到 Access 表中。
请随时回答问题并感谢您的任何回答。

 Private Sub Command9_Click()


       ' Requires reference to Microsoft Office 11.0 Object Library.

   Dim fDialog As FileDialog
   Dim varFile As Variant

   ' Clear listbox contents.
   'Me.FileList.RowSource = ""

   ' Set up the File Dialog.
   Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

   With fDialog

      .AllowMultiSelect = False


      .Filters.Add "Excel File", "*.xls"
      .Filters.Add "Excel File", "*.xlsx"

      If .Show = True Then

         'Loop through each file selected and add it to our list box.
         For Each varFile In .SelectedItems
         ' Label3.Caption = varFile

         Const acImport = 0
         Const acSpreadsheetTypeExcel9 = 8
                    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
    "Plymouth - Nominal Detail", varFile, True

         Next
         MsgBox ("Import data successful!")
         End If
End With


End Sub

最佳答案

您需要指定工作表,例如:

Private Sub Command9_Click()
   ' Requires reference to Microsoft Office 11.0 Object Library.
   Dim fDialog As FileDialog
   Dim varFile As Variant

   ' Clear listbox contents.
   'Me.FileList.RowSource = ""

   ' Set up the File Dialog.
   Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

   With fDialog

      .AllowMultiSelect = False
      .Filters.Add "Excel File", "*.xls"
      .Filters.Add "Excel File", "*.xlsx"

      If .Show = True Then

         'Loop through each file selected and add it to our list box.
         For Each varFile In .SelectedItems
         ' Label3.Caption = varFile

         Const acImport = 0
         Const acSpreadsheetTypeExcel9 = 8

         ''This gets the sheets to new tables
         GetSheets varFile

         Next
         MsgBox ("Import data successful!")
         End If
End With
End Sub


Sub GetSheets(strFileName)
   'Requires reference to the Microsoft Excel x.x Object Library

   Dim objXL As New Excel.Application
   Dim wkb As Excel.Workbook
   Dim wks As Object

   'objXL.Visible = True

   Set wkb = objXL.Workbooks.Open(strFileName)

   For Each wks In wkb.Worksheets
      DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
            wks.Name, strFileName, True, wks.Name & "$"
   Next

   'Tidy up
   wkb.Close
   Set wkb = Nothing
   objXL.Quit
   Set objXL = Nothing

End Sub

关于excel - 如何通过vba将一个包含多个工作表的excel文件导入到 Access 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21784089/

相关文章:

Excel VBA密码保护命令按钮

sql - 追加查询,跳过重复条目(重复项不是主键)

vba - 声明字符串变量时需要对象错误

php - 通过 php 将 csv 导入 mysql

excel - 使用 Excel VBA 在 excel 单元格中创建多个换行符

Excel VBA 传递组合框中值的 ID

VBA完整公式到单元格

vba - 在vba中一次循环遍历所有可用的自动筛选条件

sql - MS Access左联接SQL语法错误

VBA - 工作表的方法 'delete' 失败