我使用以下代码扫描目录中的文本文件。 然后它导入每个文本文件中的所有数据。目前我的数据被导入,每个单词都放在不同的行和列中。
我想要的是每个文本文件的每行文本都插入到一行的不同列中。
因此文本文件1可能包含:
A Cat
Mark Spence
Birmingham
当导入excel时,它应该是:
A B C
A Cat Mark Spence Birmingham
然后将文本文件2插入下面的下一行。
所以文本文件2:
A Dog
David Gray
Manchester
结果:
A B C
A Cat Mark Spence Birmingham
A Dog David Gray Manchester
请有人告诉我这里出错的地方吗?感谢
Sub Import_All_Text_Files_2007()
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
Dim strExtension As String
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Adds File Name as title on next row
Range("A1").Value = strExtension
'Sets Row Number for Data to Begin
nxt_row = Range("A1").End(xlUp).Offset(1, 0).Row
'Below is from a recorded macro importing a text file
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & strPath & strExtension, Destination:=Range("$A$" & nxt_row))
.Name = strExtension
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
'Delimiter Settings:
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileOtherDelimiter = "="
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strExtension = Dir
Loop
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
使用:
代替QueryTablesFileNum = FreeFile()
curCol = 1
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row,curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
我没有测试它,但它至少应该指导你。