babou
babou

Reputation: 237

Delete last word in a txt file

Good morning

I have a txt file named "txt" with 4 lines. And my probleme is that I want to delete the 2 last words in the 3 last lines.

This is my text in txt :

"vol"
"vui one high"  one high
"vui one front "    two high
"vuil high front "      three   high

And the words to delete is the 2 after the quote marks.


I have a code but at this moment it allow only to replace a word Here is the start of my code :

Sub CommandButton1_Click()

    Dim sBuf As String
    Dim sTemp As String
    Dim iFileNum As Integer
    Dim sFileName As String

    ' Edit as needed
    sFileName = "C:\Users\bquinty\Desktop\txt.txt"

    iFileNum = FreeFile
    Open sFileName For Input As iFileNum

    Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
    Loop
    Close iFileNum

    sTemp = Replace(sTemp, "word to remplace", "word wanted")

    'Save txt file as (if possible)

    iFileNum = FreeFile
    sFileName = "C:\Users\bquinty\Desktop\txt.txt"
    Open sFileName For Output As iFileNum

    Print #iFileNum, sTemp

    Close iFileNum


    End Sub

Thanks for all help/advice that you can give me.

Upvotes: 1

Views: 812

Answers (1)

tretom
tretom

Reputation: 625

using the answer Read/Parse text file line by line in VBA

as a beginning:

Sub test()

    Dim FileNum As Integer
    Dim DataLine As String
    Dim newDataLine() As String

    FileNum = FreeFile()
    Open "c:\Delete_NOW.txt" For Input As #FileNum

    While Not EOF(FileNum)
        Line Input #FileNum, DataLine
        newDataLine = Split(DataLine, " ")
        If UBound(newDataLine, 1) > 3 Then ReDim Preserve newDataLine(UBound(newDataLine, 1) - 3)
    Wend
End Sub

Upvotes: 1

Related Questions