【问题标题】:Issue while reading irregular tab delimited text file into Excel worksheet将不规则制表符分隔的文本文件读入 Excel 工作表时出现问题
【发布时间】:2016-05-22 12:46:36
【问题描述】:

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

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

    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   

数据和分隔符的notepad++视图。

在包括堆栈溢出在内的在线论坛的帮助下,我设法组装了以下代码。

Dim inputfile As String

Sub StartMacro_Click()

inputfile = Range("Sourcepath").Value
MsgBox (inputfile)

Call OpenAndCopyInput

End Sub

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

    Set wbO = Workbooks.Open(inputfile)

i = 1
For Each Row In VBA.Split(wbO, vbCrLf)
    j = 1
    For Each Col In VBA.Split(Row, vbTab)
        ActiveSheet.Cells(i, j).Value = Col
        j = j + 1
    Next Col
    i = i + 1
Next Row

End Sub

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

如果能有一些意见来解决这个问题,那就太好了。

【问题讨论】:

  • 你想要发生什么??您希望在导入期间将 空格 字符视为 tab 吗??
  • 嗨,我正在尝试查看并希望如果我可以将多个连续的制表符转换为单个制表符并将多个空格转换为单个空格,它将在将数据提取写入到工作表。
  • 看来您可能需要编写一个自定义函数来解析记录。

标签: vba excel text-files


【解决方案1】:

试试这个功能

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

【讨论】:

  • 你想要Destination:=Range("$A$1")还是Destination:=wsI.Range("$A$1") ??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多