我有以下代码扫描我的目录中的文本文件。在我的目录中有几个文本文件,每个文本文件都这样布局:
Text File:
Birmingham
France
Isle of White
Manchester
New-Castle
然后我尝试将每个文本文件导入excel中的新行,以便将每行文本插入该行中的新列。
Birmingham France Isle of White Manchester New-Castle
我的代码执行此操作,但它只导入一个文本文件,而不是导入目录中的所有文本文件。
有人可以告诉我哪里出错了吗?我应该得到以下结果:
Row 1
Birmingham France Isle of White Manchester New-Castle
Row 2
London Spain America Sutton Scotland
等...
代码:
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 <> ""
'Sets Row Number for Data to Begin
nxt_row = Range("A1").End(xlUp).Offset(0, 0).Row
'Below is from a recorded macro importing a text file
FileNum = 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
strExtension = Dir
Loop
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
我认为你的问题在于这一行:
nxt_row = Range("A1").End(xlUp).Offset(0, 0).Row
替换为:
nxt_row = Range("A10000").End(xlUp).Offset(1, 0).Row
或替代方案:
if Range("A1").Value = "" then
nxt_row = 1
else
if Range("A2").Value = "" then
nxt_row = 2
else
nxt_row = Range("A1").End(xlDown).Offset(1).Row
end if
end if