将现有文本文件附加到刚刚在 VBA Excel 中创建的文件

问题描述 投票:0回答:1

这里有一些关于将通过 Excel 生成的文本附加到现有文本文件的帖子。我想做相反的事情。

我从 Excel 表格中抓取了一些单元格,然后我想将大量静态文本(我们称之为页脚)附加到这个新内容中。

Sub ExportForSTK()
Dim myFile As String, TargetName As String, rng As Range, i As Integer
Dim Target(2) As String
    For i = 1 To 2 'temporary for working this out
    TargetName = ActiveSheet.Range("B5")
    Filename = TargetName & i & ".t"
    Val1= ActiveSheet.Range("F5")
    Val2 = ActiveSheet.Range("G5")
    ' ... etc.
    myFile = Application.DefaultFilePath & "Filename.txt"
    Open myFile For Output As #1
    Print #1, TextOutput(i)
    'Add contents of footer.txt to the end of Filename.txt
    Close #1
Next i

我错过了关于将 footer.txt 附加到 Filename.txt 的重要内容。

我尝试直接将 footer.txt 复制粘贴到代码中,但它充满了引号,我不想麻烦地转义它们。

excel vba
1个回答
1
投票

根据您的原始代码,这是您需要的代码。它使用文本流对象来保存页脚文本文件的内容。您可以考虑将所有文件 I/O 转换为使用 FileStreamObject。还建议使用 FreeFile 函数,该函数返回下一个可用文件编号。

参见:

链接到:文本流对象

链接至:OpenTextFile 方法

链接至:文件系统对象

Sub ExportForSTK()

Dim myFile As String, TargetName As String, rng As Range, i As Integer
Dim Target(2) As String

Dim strFooterText As String
Dim fso As Object, tso As Object
Dim intFileNumber As Integer

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

    ' Get the footer text from the text file one time only
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set tso = fso.OpenTextFile(Application.DefaultFilePath & "\Footer.txt", ForReading, True, TristateFalse)
    strFooterText = tso.ReadAll
    tso.Close

    For i = 1 To 2 'temporary for working this out
    TargetName = ActiveSheet.Range("B5")
    FileName = TargetName & i & ".t"
    Val1 = ActiveSheet.Range("F5")
    Val2 = ActiveSheet.Range("G5")
    ' ... etc.
    myFile = Application.DefaultFilePath & "\Filename.txt"
    intFileNumber = FreeFile
    
    Open myFile For Output As #intFileNumber
    
    Print #intFileNumber, TextOutput(i)
    Print #intFileNumber, strFooterText

    Close #intFileNumber
Next i

Set tso = Nothing
Set fso = Nothing

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.