如何使用 VBA 将保留前导零数字的 .CSV 导入 Excel

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

我有一个数据库,它在 .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"))
    .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

Returns or sets an ordered array of constants that specify the data types applied to the corresponding columns in the text file that you are importing into a query table. The default constant for each column is xlGeneral. Read/write Variant.