2016-12-15 35 views
0

我試圖完成在訪問VBA代碼如下:的Microsoft Access VBA進口.xlsx文件的問題:「外部表不是預期的格式」

  1. 從一個文件夾
  2. 轉換選擇一個文件從.csv文件的.xlsx
  3. 導入該文件到一個表在我的Access數據庫

我有最後一個步驟的麻煩,我能夠隱蔽的文件,但進口似乎有一個問題無線th文件格式。得到以下錯誤:「運行時error'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 
+0

標題,實際上描述您遇到的問題可能會幫助更多的人幫助... – Rdster

回答

0

在TransferSpreadsheet的,CSV文件的名稱被引用的,而不是XLSX文件 只是聲明之前加入這一行:

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

它將然後查看正確的文件名併成功完成傳輸。

+0

或者,OP可以傳遞替換的文件名,就像他在轉換中所做的那樣:'DoCmd.TransferSpreadsheet ... FileName:=替換(strFile,「.csv」,「.xlsx」)' – Parfait

+0

好電話Parfait! – tlemaster

+0

謝謝!這個作品,@tormaster你能解釋這條線是如何工作的嗎? –

相關問題