没有评估结果的TextToColumns

时间:2017-12-07 13:01:48

标签: excel-vba vba excel

我有一个带有" |" -delimeter的csv,所以我打开工作簿:

Set wb = Workbooks.Open(xl_newest_export)
Set ws = wb.Sheets(1)

并使用texttocolumns:

   ws.Range("A1:A" & CStr(lastRow)).TextToColumns Destination:=Range("A1:A" & CStr(lastRow)), DataType:=xlDelimited, _
        TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, DecimalSeparator:=".", Other:=True, OtherChar _
        :="|"

然而,由于Excel会对文本进行评估,因此会失败 - 一些双打将转换为日期。例如 " 1" - > " 01.01.1900"

如何在没有评估的情况下实现上述目标?

修改: 正如评论中所建议的那样 - Fieldinfo就是解决方案。但是我尝试构建一个数组字符串...例如"阵列(阵列(3,1)...)"但这也失败了..

1 个答案:

答案 0 :(得分:1)

使用数据填充 A 列后,请改用:

Sub PiedPipper()
    Dim rng As Range, r As Range, pipe As String

    Cells.NumberFormat = "@"
    Set rng = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    pipe = "|"
    For Each r In rng
        ary = Split(r.Value, pipe)
        r.Resize(1, UBound(ary) + 1) = ary
    Next r
End Sub

修改#1:

使用此功能将.csv数据添加到 A

列中
Sub GetCVSData()
   Dim FilesToOpen
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction
   Dim ary, bry, DQ As String
   DQ = Chr(34)

   FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")

   Close #1
   Open FilesToOpen For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      With Cells(j, 1)
        .NumberFormat = "@"
        .Value = TextLine
    End With
      j = j + 1
   Loop

   Close #1
End Sub