【问题标题】:Microsoft Access VBA import .xlsx file issues: "external Table not in the expected format"Microsoft Access VBA 导入 .xlsx 文件问题:“外部表不是预期格式”
【发布时间】:2016-12-15 15:34:03
【问题描述】:

我正在尝试在访问 VBA 代码中完成以下操作:

  1. 从文件夹中选择一个文件
  2. 将文件从 .csv 转换为 .xlsx
  3. 将该文件导入我的 Access 数据库中的表中

我在最后一步遇到问题,我可以隐藏文件,但在导入时文件格式似乎存在问题。得到以下错误:“运行时错误'3274'“外部表不是预期的格式”

有人知道可能的解决方案吗?

代码:

Private Sub Command1_Click()
Dim fd As Office.FileDialog
Dim varFile As Variant

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd
    .Title = "Choose the File you would like to import"
    .AllowMultiSelect = False
    .InitialFileName = "Z:\location\"
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xls*"
    .Filters.Add "All Files", "*.*"
    .Filters.Add "CSV Files", "*.csv"

    If .Show = True Then
        For Each varFile In .SelectedItems

            Dim xlApp As Object
            Dim wb As Object
            Dim strFile As String

            Set xlApp = CreateObject("Excel.Application")
            strFile = varFile
            Set wb = xlApp.Workbooks.Open(strFile)

            With wb
                ' where 56 is value of excel constant xlExcel8
                .SaveAs FileName:=Replace(strFile, ".csv", ".xlsx"), FileFormat:=51
            End With
            'clean up
            Set wb = Nothing
            xlApp.Quit
            Set xlApp = Nothing

     MsgBox ("Your File has been converted and is currently being imported to this database") 'Should come up as a success

           DoCmd.TransferSpreadsheet _
                TransferType:=acImport, _
                SpreadsheetType:=acSpreadsheetTypeExcel9, _
                TableName:="C-Report", _
                FileName:=varFile, _
                HasFieldNames:=True
            MsgBox ("Your Import has been complete") 'Should come up as a sucess message
        Next
    Else
        'stop execution if nothing selected
        MsgBox ("There has been an error with your import. Please try again.")
        End
    End If
End With
End Sub

【问题讨论】:

  • 实际描述您遇到的问题的标题可能有助于让更多人获得帮助...

标签: excel ms-access import vba


【解决方案1】:

在 TransferSpreadsheet 中,引用的是 csv 文件的名称,而不是 xlsx 文件。 在该语句之前添加这一行:

varFile = Left(varFile, (InStrRev(varFile, ".", -1, vbTextCompare) - 1)) & ".xlsx"

然后它将看到正确的文件名并成功完成传输。

【讨论】:

  • 或者,OP 可以传递替换的文件名,就像他在转换中所做的那样:DoCmd.TransferSpreadsheet ...FileName:=Replace(strFile, ".csv", ".xlsx")
  • 好叫冻糕!
  • 谢谢!这行得通,@tlemaster 你能解释一下这条线是如何工作的吗?
  • InStrRev(varFile, ".", -1, vbTextCompare) 返回文件名中最后一个句点的位置(如果有多个句点)。环绕它的 Left 命令只返回不带后缀的文件名。之后 & ".xlsx" 将我们想要的后缀添加到文件名的末尾。我希望这是有道理的!
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
相关资源
最近更新 更多