簡體   English   中英

如何導入。CSV 使用 VBA 將前導零數字保留到 Excel

[英]How to import .CSV preserving leading zeros numbers into Excel using VBA

我有一個數據庫,可以提取 in.CSV 並使用 VBA 我將數據導入 Excel 但導入時,ID 中缺少一些前導零

即使我在 Excel 中打開 .CSV 文件,這些零也不存在。 這是我正在使用的當前代碼:

sub import()
Dim File As String

MsgBox "Please select the Extract File", vbInformation

With Application.FileDialog(msoFileDialogFilePicker)
    .Filters.Clear
    .InitialFileName = "\\route"
    .AllowMultiSelect = False
    .Filters.Add "csv", "*.csv"
    If .Show = -1 Then
        File = .SelectedItems(1)
    Else
        MsgBox "Please, select the file then try again", vbExclamation
        Exit Sub
    End If
End With

With Worksheets("Data Paste").QueryTables.Add(Connection:= _
    "TEXT;" & File _
    , Destination:=Worksheets("Data Paste").Range("$A$1"))
    .Name = "FileName"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 65001
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileTrailingMinusNumbers = True
    .TextFileColumnDataTypes = Array(xlTextFormat)
    .Refresh BackgroundQuery:=False
End With
Exit Sub

我嘗試事先將工作表的格式更改為 TEXT,但即使該數據是文本格式,這些零仍然丟失。

編輯1:我用記事本打開了.CSV,那些前導零就在那里。 但不是當我用 Excel 打開它時

.TextFileColumnDataTypes = Array(xlTextFormat) 

只會將文本格式應用於第一列。 您需要添加與需要以文本格式導入的每一列對應的值。

https://docs.microsoft.com/en-us/office/vba/api/excel.querytable.textfilecolumndatatypes

返回或設置一個有序的常量數組,這些常量指定應用於要導入查詢表的文本文件中的相應列的數據類型。 每列的默認常量是 xlGeneral。 讀/寫變體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM