![](/img/trans.png)
[英]Import multiple text files to 1 cell and a new row in Excel using VBA?
[英]Excel VBA: Import data from all text files in a directory onto a new row in excel?
我正在使用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
请有人能告诉我一种做我需要的方法吗? 提前致谢
您需要将以下代码段与代码合并,在其中替换硬编码的文件路径和文件名。 另外,在打开新文件时,您还需要确保拥有正确的索引。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.