我正在使用VBA将单个文本文件中的所有数据导入到excel中的新行中,然后一旦导入文本文件中的数据,就将文本文件移动到另一个位置/目录。我做了这么多。
但是现在我在目录中有多个文本文件,并希望从每个文本文件中获取数据并将其插入到新行中,这样我最终得到以下结果:
Text File 1
A
B
C
D
Text File 2
T
L
V
P
Excel:
Column A Column B Column C Column D
A B C D
T L V P
这是我的代码:
Sub ImportFile()
Dim rowCount As Long
rowCount = ActiveSheet.UsedRange.Rows.Count + 1
If Cells(1, 1).Value = "" Then rowCount = 1
Close #1
Open "Z:\Incident Logs\Unactioned\IN94LQ3Z.txt" For Input As #1
A = 1
Do While Not EOF(1)
Line Input #1, TextLine
Cells(rowCount, A) = TextLine
A = A + 1
Loop
Close #1
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
srcPath = "Z:\Incident Logs\Unactioned\"
destPath = "Z:\Incident Logs\Actioned\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir
Loop
Next
End Sub
请有人能告诉我一种做我需要的方法吗?提前致谢
答案 0 :(得分:0)
您需要将以下代码段与代码合并,以替换硬编码文件路径和文件名。此外,您还需要确保在打开新文件时正确使用索引。
Sub AllFilesInFolder()
Dim myFolder As String, myFile As String
myFolder = Application.FileDialog(msoFileDialogFolderPicker)
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
myFolder = .SelectedItems(1)
End If
End With
myFile = Dir(myFolder & "\*.txt") '
Do While myFile <> ""
Open myFolder & "\" & myFile For Input As #1
.....
myFile = Dir
Loop
End Sub