【发布时间】:2025-11-30 16:30:01
【问题描述】:
我知道有很多不同的主题可以涵盖这个问题,但没有什么对我有用...我有 .xls 工作簿,其中包含 3 个工作表(Sheet1、Sheet2 和 Sheet3)。
每个工作表将有 65536 行(Sheet3 目前将有 25+ 行)。我在下面的链接上找到了一个代码,它应该可以完成这项工作......但是......它没有。它只会导入 25k 行。此外,只有 Sheet1 会有标题,Row1 上的 Sheet2 和 Sheet3 会有数据。
Import Data from All Worksheets in a single EXCEL File into One Table via TransferSpreadsheet (VBA)
我的 VBA 只从第一个选项卡导入 Excel 文件。有没有办法修改它,以便导入所有三个工作表,其中只有第一个有标题?
Private Sub cmdButton_Click()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\Folder\"
strTable = "dbo_tblTest"
strFile = Dir(strPath & "*.xlsx")
If Right(strPath, 1) <> "\" Then
strPath = strPath & "\"
End If
If Dir(strPath & "*.*") = "" Then
MsgBox "The folder doesn't contain (visible) files"
Else
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Once purged LOOP file import
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' LOOP TO MOVE FILES IN ARCHIVE FOLDER
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dim fso As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
FromPath = "S:\Folder" '~~> Change
ToPath = "S:\Folder\Archive" '~~> Change
FileExt = "*"
'~~> You can use *.* for all files or *.doc for word files
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set fso = CreateObject("scripting.filesystemobject")
If fso.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If fso.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
fso.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
Kill "S:\Folder\*"
MsgBox "Files Successfully Imported"
End If
End Sub
【问题讨论】:
-
你试过Excel内置的macro recorder吗?如果您手动执行一次导入,Excel 会将您的操作记录为 VBA。然后,您可以根据需要查看、编辑、调整和重新运行代码。
-
您已链接代码。请显示基于它的尝试。必要的修改很小。
-
@destination-data 这正是我目前所拥有的。打开文件的 Excel 上的 VBA 从工作表拆分为 3 个工作簿,然后将它们连接起来并吐出一个 excel 文件,其中所有记录都在一张表上......但是,我正试图摆脱基于 Excel 的操作并使用 Access 导入...除非您建议使用 Excel VBA 在 Access 中执行相同的操作...
-
好吧,我误会了。你在这里有三个问题。 1) 为什么代码没有导入所有记录? 2)如何打开/关闭标题? 3) 如何从多个选项卡导入?严格来说,您应该发布三个单独的问题。一次解决所有问题可能会变得复杂。高水平的答案是 1) 您是否收到任何错误消息,如果收到,它们是什么? 2) 阅读TransferSpreadsheet 方法的HasFieldNames 参数。 3) 你需要一个循环。