How to use “append” command on specific position in a text file using Visual Basic?

前端 未结 1 1127
执念已碎
执念已碎 2021-01-25 23:33

Text file:

test1

test2

test3

test4

I want to write after \"test2\" - something. I tried first time to open the file and I read the pos

相关标签:
1条回答
  • 2021-01-26 00:19

    You could use:

    Print #3, "This is my text to write to file."
    

    Example here. If you need more information that this, please post the code you have so far.


    Edit:

    Try this:

    Sub testWriteFile()
    
        Const Test_Filename = "c:\testfile.txt"
        Const findText = "test2"  ' what to find in file
        Const insertText = "!!!SOMETHING!!!"  ' what to put in line after [findText]
    
        Dim LinesRead As Integer, LinesInserted As Integer, outputText As String
    
        'If file doesn't exist then exit sub
        If Dir(Test_Filename) = "" Then
            MsgBox ("Cannot find the file")
            Exit Sub
        End If
    
        Open Test_Filename For Input As #3
        Do While Not EOF(3)
    
                'read line from input file
                Line Input #3, strLine
                LinesRead = LinesRead + 1
    
                'write line to output string
                outputText = outputText & strLine & vbCrLf
    
                'if line says
                If LCase(Left(strLine, Len(findText))) = LCase(findText) Then
                        outputText = outputText & insertText & vbCrLf  ' "insert" this line at the current position of output string
                        LinesInserted = LinesInserted + 1
                End If
        Loop
    
        'close output file
        Close #3
    
    
        'replace output file with output string
        Open Test_Filename For Output As #3
        Print #3, outputText
        Close #3
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题