【问题标题】:Importing separate rows and columns from a .txt file into an excel worksheet(vba)将 .txt 文件中的单独行和列导入 excel 工作表(vba)
【发布时间】:2013-11-30 14:56:07
【问题描述】:

我一直在关注将 .txt 文件导入 excel 的示例,唯一的问题是我似乎无法弄清楚如何使这一行将数据分成 2 个单独的列

Set oFS = oFSO.OpenTextFile(filePath)
Do While Not oFS.AtEndOfStream
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = oFS.ReadLine
Loop
oFS.Close

我需要导入的 .txt 文件有 2 列和 N 行,我的问题是,如果不将 .txt 文件中的两列都写入 excel 工作表的 1 列,我该如何读取它?

N
X  Y
X2 Y2
X3 Y3
etc..

这就是 .txt 文件的外观。提前致谢。

【问题讨论】:

  • 需要分成两列的字段是什么分开的??

标签: vba excel


【解决方案1】:

这将完成这项工作,使用 VBA Split() 函数:

Sub sof20301663ImportTextFile()
  Const ForReading = 1, ForWriting = 2, ForAppending = 3

  Dim i, iup, varArray
  Dim fso As Object, tso As Object
  Dim strFilePath, strLine      

  ' adapt here your text file name:      '
  strFilePath = "MyTestFile.txt"

  Set fso = CreateObject("Scripting.FileSystemObject")      '
  ' get TextStream:

  Set tso = fso.OpenTextFile(strFilePath, ForReading)

  i = 2
  Do While Not tso.AtEndOfStream        '
    ' read a line from the file:
    strLine = tso.ReadLine
    ' split with separator tab:
    varArray = Split(strLine, vbTab)
    iup = UBound(varArray)
    ' split with separator space:

    If (iup <= 0) Then
      varArray = Split(strLine, " ")
      iup = UBound(varArray)
    End If

    ' fill a cell: using strLine as range address:

    strLine = "A" & i
    Range(strLine).Value = varArray(0)
    Range(strLine).NumberFormat = "General"

    ' if there is more then two words, fill cell 2:

    If (iup > 0) Then
      strLine = "B" & i
      Range(strLine).Value = varArray(1)
      Range(strLine).NumberFormat = "General"
    End If        
    i = i + 1

  Loop

  ' clean objects:

  tso.Close
  Set tso = Nothing

  Set fso = Nothing
End Sub

MyTestFile.txt 的内容:

50
info    computer
image   logo
tendancy    soulant

Excel结果:

【讨论】:

  • 感谢您的快速回复,就像一个魅力,评论部分对像我这样的 VBA 新手也很有帮助。如果我只能要求 1 个加法,我在哪里可以设置将 .txt 文件中的数据作为数字而不是文本导入的条件?
  • 很高兴分享一些东西。
  • 是的,它以相同的方式处理它们,我认为我自己的措辞不正确。鉴于导入的文本由数字组成,有没有办法将单元格格式化为不是文本类型但第一?与其在导入后手动格式化,不如用一些简单的代码行来完成?
  • 非常感谢大家的帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
相关资源
最近更新 更多