2016-02-23 78 views
0

我是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" 
+0

你想複製所有文件內容並粘貼到你的'allFiles.py'中? – ZwoRmi

+0

對,我希望他們都合併成一個。 – Ellone

+0

_bash_與此有什麼關係? – user3439894

回答

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 
+0

從來沒有在'GetFileText(pathFile)'中使用'pathFile'嗎? 另外,它不應該以'End Function'結束 – Ellone

+0

@Ellone是的!答案已更新。 – ZwoRmi

+0

嗯,我試過我的測試:'textToWrite = GetFileText(ThisWorkbook.Path&「\ file.py」)oFile.writeLine textToWrite',它似乎沒有工作。 'getFileText'是否返回任何內容?如果可以,它可以用作WriteLine參數嗎? – Ellone