从.txt文件导入单独的行和列到Excel工作表(vba)

我一直在下面的例子导入.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 XY X2 Y2 X3 Y3 etc.. 

多数民众赞成.txt文件必须看。 提前致谢。

这将使用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结果:

在这里输入图像说明