如何复制粘贴表从许多txt文件到1 excel表?



我需要做的步骤:

  1. 在Excel
  2. 中打开所有必要的文件(来自同一文件夹)
  3. 对于第一个文件,从第6行复制到表的底部。对于第二个文件和后续文件,从第7行复制到表的底部(注意每个文件有不同数量的表行)。(理由是第1-5行是不相关的,第6行有标题,我只希望标题在表中出现一次)
  4. 粘贴到主excel表格中,但不能与前面的行重叠
  5. 用逗号分隔主excel表(文本到列)
  6. 关闭除主excel表以外的所有文件

尝试谷歌的各个步骤,但每一步的代码不能很好地相互工作,导致无数的错误,所以我放弃了,并试图记录宏,但我没有得到一个"for"循环。

我刚刚测试了下面的代码

Sub Read_Texts()
'Variable Declaration
Dim sFilePath As String
Dim sFileName As String
'Specify File Path
sFilePath = "C:UsersuseDesktopNew folder"
'Check for back slash
If Right(sFilePath, 1) <> "" Then
sFilePath = sFilePath & ""
End If

sFileName = Dir(sFilePath & "*.txt")
Do While Len(sFileName) > 0
If Right(sFileName, 3) = "txt" Then
'Display file name in immediate window
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long

Open sFileName For Input As #hf
lines = Split(Input$(LOF(hf), #hf), vbNewLine)
Close #hf

If sFileName = "file1.txt" Then
For i = 5 To UBound(lines)
Debug.Print "File 1 Line"; i; "="; lines(i)
Next
Else
For i = 6 To UBound(lines)
Debug.Print "File 1 Line"; i; "="; lines(i)
Next
End If
End If
'Set the fileName to the next available file
sFileName = Dir
Loop
End Sub

根据你的文件夹路径改变C:UsersuseDesktopNew folder,在这里你可以对返回的Debug.Print "File 1 Line"; i; "="; lines(i)

行做任何事情

最新更新