Microsoft Access VBA导入.xlsx文件问题:"外部表格不符合预期格式"

时间:2016-12-15 15:34:03

标签: vba excel-vba ms-access import access-vba

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

  1. 从文件夹中选择文件
  2. 将文件从.csv转换为.xlsx
  3. 将该文件导入Access数据库中的表
  4. 我在最后一步遇到问题,我能够隐藏文件,但在导入时似乎存在文件格式问题。得到以下错误:"运行时错误' 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
    

1 个答案:

答案 0 :(得分:0)

在TransferSpreadsheet中,正在引用csv文件的名称而不是xlsx文件。 在该声明之前添加此行:

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

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