MS Access VBA打开文本文件并写入特定行,而不会覆盖该文件

时间:2019-05-13 21:58:05

标签: vba ms-access access-vba

我有一个文本文件,想要添加页眉和页脚。我不想覆盖第一行或最后一行,而是想添加一个新的第一行并将一行添加到文件末尾。

下面的函数适用于追加到文件的底部,但是我希望能够控制插入行的位置。谢谢!

Function WriteToText(sFile As String, sText As String)

    On Error GoTo Err_Handler
    Dim iFileNumber           As Integer

    iFileNumber = FreeFile                   ' Get unused file number
    Open sFile For Append As #iFileNumber    ' Connect to the file
    Print #iFileNumber, sText                ' Append our string
    Close #iFileNumber                       ' Close the file   Exit_Err_Handler:
    Exit Function   Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: Txt_Append" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler End Function

1 个答案:

答案 0 :(得分:1)

您如何完成这样的任务:

  1. 将整个文件读取为字符串(Open For Input
  2. 添加所需的数据:S = "header line" & vbCrLf & S & vbCrLf & "footer line"
  3. 将整个字符串写入文件,并将其覆盖(Open For Output