Excel VBA实现将现有文本文件追加至新创建文件的技术问询
解决方法
直接读取footer.txt的完整内容再追加到目标文件,完全不用手动转义引号。修改后的代码如下:
Sub ExportForSTK() Dim myFile As String, TargetName As String, footerPath As String Dim i As Integer, footerContent As String Dim fileNum As Integer ' 这里填footer.txt的实际路径,和Excel同目录就用ThisWorkbook.Path footerPath = ThisWorkbook.Path & "\footer.txt" For i = 1 To 2 ' 临时测试循环 TargetName = ActiveSheet.Range("B5").Value ' 修正文件名拼接,避免路径直接连在一起出错 myFile = Application.DefaultFilePath & "\" & TargetName & i & ".t" ' 第一步:写入Excel提取的内容到新文件 fileNum = FreeFile() Open myFile For Output As #fileNum Print #fileNum, TextOutput(i) ' 假设TextOutput是你已经写好的生成内容的函数 Close #fileNum ' 第二步:一次性读入footer.txt的全部内容 fileNum = FreeFile() Open footerPath For Input As #fileNum footerContent = Input$(LOF(fileNum), fileNum) Close #fileNum ' 第三步:把footer内容追加到目标文件末尾 fileNum = FreeFile() Open myFile For Append As #fileNum Print #fileNum, footerContent Close #fileNum Next i End Sub
重点说明
- 路径要对:如果
footer.txt不在Excel文件同目录,直接把footerPath改成绝对路径(比如"C:\YourFolder\footer.txt")。 - 用FreeFile():别硬写#1这种文件号,避免和其他打开的文件冲突。
- 一次性读取:
Input$(LOF(fileNum), fileNum)直接读整个文件,比逐行读效率高,还能保留原文件的格式。 - 追加模式:
Open ... For Append不会覆盖原有内容,只会把新内容加在文件最后。
内容的提问来源于stack exchange,提问作者Spartacus
相关产品推荐
相关产品推荐

