将不规则制表符分隔的文本文件读入Excel工作表时发出问题

时间:2016-05-22 12:46:37

标签: vba excel-vba text-files excel

我正在尝试将制表符分隔的文本文件读入Excel工作表(这是我必须做的众多转换的第一步)。问题是输入文件不是一个干净的分隔文件。因此,标题最终在单个单元格中,后面是单个单元格中的许多行,但另一组行被分成多个列。有没有办法在读取文件时清理分隔符并将清理后的版本放入工作表?

输入样本(实际文件为更多列):

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date dob;

数据和分隔符的记事本++视图。

enter image description here

借助包括堆栈溢出在内的在线论坛,我设法汇编了以下代码。

    Name    Cost Elem.  Object  Year        Fixed val.      Fixed val.      Fixed val.    

*   RB-001-XXXXXXXXXXX costs    980808  10000003             8,677.89       14,441.99     

*   RB-001-YYYYYYYYYYY costs    980808  10000012            16,116.09       24,757.70     

*   RB-007-ZZZZZZZZZZZ Mgmt &Wrkshop    980204  10000118                 0.03            0.03   

导入后,数据在工作表中如下所示:

enter image description here

有一些意见可以解决这个问题。

1 个答案:

答案 0 :(得分:0)

试试这个功能

Sub OpenAndCopyInput()
  Dim wbI As Workbook, wbO As Workbook
  Dim wsI As Worksheet

  Set wbI = ThisWorkbook
  Set wsI = wbI.Sheets("datasheet") '<~~ Sheet where you want to import

  With wsI.QueryTables.Add(Connection:="TEXT;" & inputfile), _
          Destination:=Range("$A$1"))
    .Name = "NameOfYourFile"  'Just the name without path and file extension
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 1252
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = True
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1) 'For each column you want to import you need a ",1"
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
  End With
End Sub