【问题标题】:How to change column formats during csv import如何在 csv 导入期间更改列格式
【发布时间】:2018-02-23 07:49:13
【问题描述】:

我通过

导入一个 .csv 文件
Sub Datei_Importieren()
  Dim strFileName As String, arrDaten, arrTmp, lngR As Long, lngLast As Long
  Const cstrDelim As String = VBA.Constants.vbTab 'Trennzeichen

  With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .Title = "Datei wählen"
    .InitialFileName = "C:\Test\*.csv"  'Pfad anpassen
    .Filters.Add "CSV-Dateien", "*.csv", 1
    If .Show = -1 Then
      strFileName = .SelectedItems(1)
    End If
  End With

  If strFileName <> "" Then
    Application.ScreenUpdating = False
    Open strFileName For Input As #1
    arrDaten = Split(Input(LOF(1), 1), vbCrLf)
    Close #1
    For lngR = 1 To UBound(arrDaten)
      arrTmp = Split(arrDaten(lngR), cstrDelim)
      If UBound(arrTmp) > -1 Then
        With ActiveSheet
          lngLast = .Cells(Rows.Count, 1).End(xlUp).Row + 1
          lngLast = Application.Max(lngLast, 10)
          .Cells(lngLast, 1).Resize(, UBound(arrTmp) + 1) _
            = Application.Transpose(Application.Transpose(arrTmp))
        End With
      End If
    Next lngR
  End If
End Sub

该功能完美运行,但我想将 D 列设置为文本,但找不到参数。有谁能帮帮我吗?

【问题讨论】:

  • .Range("D1:D" &amp; lngLast).NumberFormat = "@"
  • 您是否总是希望它显示 3 位数字?如果是这样,请使用="000"
  • 试试="###"="##0"
  • 我只记得您可以像手动操作一样通过 vba 导入为 CSV。这可能是更好的方法,因为您可以直接在其中定义数据类型。获得它的一种简单方法是记录自己手动执行的宏(然后根据需要进行调整)。

标签: excel csv import vba


【解决方案1】:

此代码适用于我

Sub Import_Zeros()

    Application.CutCopyMode = False
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\test\export.xls" _
        , Destination:=Range("$A$1"))
        .Name = "export"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 936
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 2, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("D19").Select
    Application.WindowState = xlMaximized
End Sub

您可以在这里调整格式:Array(1, 1, 1, 2, 1, 1, 1, 1)

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 2019-09-26
    • 2012-12-31
    • 2018-05-22
    • 2012-10-22
    • 1970-01-01
    • 2021-03-12
    • 2022-07-20
    • 2023-04-05
    相关资源
    最近更新 更多