vb怎样把多个txt文本文件合并为一个文本文件?
2个回答
展开全部
其实方法有很多,我就列举常用的两个吧...
方法一此猛:
循环获得文运凳件夹里的文件;
判断是否为文本文件;
按行读取文本文件;。。。
下面我用Dir()函数获得文件夹里的文件,文件将按“文件名”排序。也可以结合文件系统来做。
Private Sub Command1_Click()
Dim FolderPath As String, FileName As String, fnum1 As Integer, fnum2 As Integer
Dim sL As String
FolderPath = "D:\123\"
fnum1 = FreeFile
Open FolderPath & "tmp.txt" For Output As fnum1
FileName = Dir(FolderPath)
Do Until FileName = ""
If LCase(Right(FileName, 4)) = ".txt" And FileName <> "tmp.txt" Then
fnum2 = FreeFile
Open FolderPath & FileName For Input As fnum2
Do Until EOF(fnum2)
Line Input #fnum2, sL
Print #fnum1, sL
Loop
Print #fnum1,
Close #fnum2
End If
FileName = Dir()
Loop
Close #fnum1
End Sub
方法二:
如果这些文本文件都是ANSI编码,那么可以使用命令行的Copy语句。
代码确实能做到很简洁,但就没有灵活性了。其中,文件将按“文件名”排序。
Private Sub Command1_Click()
Dim FolderPath As String
FolderPath = "D:\123\"
Shell "cmd.exe /c Copy """ & FolderPath & "*.txt"" """ & FolderPath & "旁扒旅tmp.txt"""
End Sub
另外,这种方法可以用bat文件来实现。
方法一此猛:
循环获得文运凳件夹里的文件;
判断是否为文本文件;
按行读取文本文件;。。。
下面我用Dir()函数获得文件夹里的文件,文件将按“文件名”排序。也可以结合文件系统来做。
Private Sub Command1_Click()
Dim FolderPath As String, FileName As String, fnum1 As Integer, fnum2 As Integer
Dim sL As String
FolderPath = "D:\123\"
fnum1 = FreeFile
Open FolderPath & "tmp.txt" For Output As fnum1
FileName = Dir(FolderPath)
Do Until FileName = ""
If LCase(Right(FileName, 4)) = ".txt" And FileName <> "tmp.txt" Then
fnum2 = FreeFile
Open FolderPath & FileName For Input As fnum2
Do Until EOF(fnum2)
Line Input #fnum2, sL
Print #fnum1, sL
Loop
Print #fnum1,
Close #fnum2
End If
FileName = Dir()
Loop
Close #fnum1
End Sub
方法二:
如果这些文本文件都是ANSI编码,那么可以使用命令行的Copy语句。
代码确实能做到很简洁,但就没有灵活性了。其中,文件将按“文件名”排序。
Private Sub Command1_Click()
Dim FolderPath As String
FolderPath = "D:\123\"
Shell "cmd.exe /c Copy """ & FolderPath & "*.txt"" """ & FolderPath & "旁扒旅tmp.txt"""
End Sub
另外,这种方法可以用bat文件来实现。
更多追问追答
追问
代码测试可行。但我把你代码中的"D:\123\"更换成App.Path & "\文件"怎么不行了呢?
另外,ANSI编码的文件不能按方法一进行合并吗?
追答
更换成App.Path & "\文件\"(少了一个斜杠)
ANSI编码的文件可以按方法一进行合并。我只是说,非ANSI编码的文本文件不能用方法二。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询