Workbooks.OpenText not parsing csv files properly Excel 2016

前端 未结 4 512
栀梦
栀梦 2020-12-21 11:47

I\'m pretty sure this worked properly in previous versions of Excel

Test File:

d/mm/yyyy hh:mm:ss
5/12/1999 6:01:12
30/11/2001 5:00:00
4条回答
  •  清酒与你
    2020-12-21 11:59

    CSV and Text are really not the same for Excel. Not only that the delimiter settings are very special for CSV and are not setable using a parameter in Workbooks.OpenText. Also other parameters like field types (FieldInfo) will also not be respected while opening CSV files. And also the unicode handling is a very special case for CSV and is signly different from Text.

    You could try using QueryTables like so:

    Sub foo1()
        Dim WB As Workbook
        Dim sFN As String
        Dim FD As FileDialog
    
    Set FD = Application.FileDialog(msoFileDialogFilePicker)
    
    With FD
        .AllowMultiSelect = False
        .Filters.Add "Text or CSV", "*.txt, *.csv", 1
        .Show
        sFN = .SelectedItems(1)
    End With
    
    Set WB = Workbooks.Add
    
    With WB.Worksheets(1).QueryTables.Add(Connection:= _
        "TEXT;" & sFN & "", Destination:=Range("$A$1"))
        .Name = "test"
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(xlDMYFormat, xlGeneralFormat)
        .Refresh BackgroundQuery:=False
    End With
    
    End Sub
    

    But using QueryTables of course you must be careful not adding them multiple times without necessary but refreshing them instead or first deleting them and then adding them again.

提交回复
热议问题