将文件附加到一个文件中

时间:2016-02-23 12:10:29

标签: vba shell excel-vba command-line excel

我是VBA和Shell的新手,但是我需要使用一些。

我正在尝试将几个文件追加在一起:

这是我到目前为止所得到的:

Dim fso As Object
Dim oFile As Object

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(ThisWorkbook.Path & "\allFiles.py", True)

Shell "copy /b " & ThisWorkbook.Path & "\file1.py + " & ThisWorkbook.Path & "\file2.py + " & ThisWorkbook.Path & "\file3.py " & ThisWorkbook.Path & "\allFiles.py"

1 个答案:

答案 0 :(得分:0)

仅使用VBA,您可以执行以下操作:

Sub GetOneFile()
    Dim fso As Object, oFile As Object, pathFileAllFiles As String 
    pathFileAllFiles = ThisWorkbook.Path & "\allFiles.py"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile(pathFileAllFiles, True)

    Dim pathsFiles(3) As String, i As Integer, textToWrite As String, pathFile As Variant
    pathFiles(0) = ThisWorkbook.Path & "\file1.py"
    pathFiles(1) = ThisWorkbook.Path & "\file2.py"
    pathFiles(2) = ThisWorkbook.Path & "\file3.py"

    For Each pathFile As String In pathFiles
        textToWrite = GetFileText(pathFile)
        oFile.WriteLine textToWrite
    Next
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing    
End Sub

Function GetFileText(pathFile) as String
    Dim lineData As String, result As String
    Dim ff As Integer
    ff = FreeFile
    Open pathFile For Input As #ff
    Do Until EOF(ff)
        Line Input #ff, lineData
        result = result & VbCrlf & lineData
    Loop
    Close #ff
    GetFileText = result
End Function