Excel,匯入精靈,偵測到錯誤的檔案類型

Excel,匯入精靈,偵測到錯誤的檔案類型

每個月,我都有幸將每日的管道分隔文件編譯成每月的 Excel 工作簿。我使用匯入精靈將文字檔案轉換為工作簿中的工作表。我一次打開所有 30 個文件,並按照嚮導的提示對每個文件進行操作。此嚮導通常可以正確地偵測到檔案是用豎線分隔的。但是,在每批文件中,只有一次,它將文件類型從“分隔”更改為“固定寬度”。每個文件的格式相同,日期|部門|帳戶|類型|金額等......。每個欄位在所有文件中都包含相似的資料。所有日期均為 8 個字元;所有部門均為 5 個字元;所有帳戶均為 6 個字元; ETC…。

為什麼 Excel 突然無法辨識文件的分隔格式?
為什麼只有 1 個文件?

它確保我在集中註意力嗎?

Excel 2013 和 Excel 365 Pro (MSO 16.0) 中都會發生這種情況

答案1

如果您了解 VBA,則可以使用下列宏,該巨集將詢問檔案名稱並強制將其作為管道分隔匯入:

Sub Test()
    Dim Filter As String, Title As String
    Dim FilterIndex As Integer
    Dim FileName As Variant

    ' File filters
    Filter = "Text Files (*.dat),*.dat," & "All Files (*.*),*.*"

    ' Default Filter to *.*
    FilterIndex = 3

    ' Set Dialog Caption
    Title = "Select a File to Open"

    ' Select Start Drive & Path
    ChDrive ("G:")
    ChDir ("G:\Scot\MS Excel")

    With Application
        ' Set File Name to selected File
        FileName = .GetOpenFilename(Filter, FilterIndex, Title)
        ' Reset Start Drive/Path
        ChDrive (Left(.DefaultFilePath, 1))
        ChDir (.DefaultFilePath)
    End With

    ' Exit on Cancel
    If FileName = False Then
        MsgBox "No file was selected."
        Exit Sub
    End If

    ' Import File
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & FileName, Destination:=Range("A1"))
        .TextFileParseType = xlDelimited
        .TextFileOtherDelimiter = "|"
        .Refresh BackgroundQuery:=False
    End With
End Sub

在「選擇啟動磁碟機和路徑」下方的程式碼中輸入您自己的值。

來源

相關內容