如何強制 Excel 將 CSV 中的日期視為巨集中的文本

如何強制 Excel 將 CSV 中的日期視為巨集中的文本

我有一個宏,可以讓使用者選擇一個 CSV 文件,然後對其進行操作。但是,它將包含 1/2/12 等內容的儲存格視為日期。我需要將這些字串保留為文本,而不是日期。

我知道我可以透過 1) 啟動一個新工作表 2) 匯入 CSV 而不是打開它來做到這一點。將日期列設定為“文字”並完成。

問題是:如何中斷“資料”>“導入”以便使用者可以選擇檔案。之後,巨集應該繼續設定列的格式,完成匯入並執行資料操作。

編輯:這是巨集的相關程式碼:

ChDir "C:\RoomTimerData\"

MyFile = Application.GetOpenFilename("逗號分隔值 (.csv),.csv”)

工作簿.開啟檔案名稱:=MyFile

答案1

通常,人們會為每個匯入的欄位選擇資料類型,作為文字匯入對話方塊的第 3 步(共 3 步)。為了避免格式錯誤,只需使用文字作為格式,你就很好了。

但是,您似乎使用 VBA 巨集來匯入 CSV 檔案。所以我就記錄了這樣一個未損壞的文字進口:

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\test.csv", Destination:=Range("$A$1"))
    .Name = "test_1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 850
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(2, 1) 'THIS IS THE MAGIC LINE!
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

另外,請查看 excel-help 中的範例TextFileColumnDataTypes

Set shFirstQtr = Workbooks(1).Worksheets(1) 
Set qtQtrResults = shFirstQtr.QueryTables _
        .Add(Connection := "TEXT;C:\My Documents\19980331.txt", _
        Destination := shFirstQtr.Cells(1, 1))
With qtQtrResults
    .TextFileParseType = xlFixedWidth
    .TextFileFixedColumnWidths = Array(5, 4)
    .TextFileColumnDataTypes = _
        Array(xlTextFormat, xlSkipColumn, xlGeneralFormat)
    .Refresh
End With

您可以使用以下格式:

  • xl通用格式
  • xl文字格式
  • xl跳過列
  • xlDMY格式
  • xlDYM格式
  • xlEMD格式
  • xlMDY格式
  • xlMYD格式
  • xlYDM格式
  • xlYMD格式

相關內容