1

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.

babou
  • 237
  • 1
  • 14
  • You can use the [`split`](http://www.exceltrick.com/formulas_macros/vba-split-function/) function to split the `sTemp` into single lines (delimiter should be vbcrlf or vbcr depends on your txt file). And then again `split` to split the last 2 lines into singe words (delimiter is a blank). After that you need just remove the last 2 entries and put the string back together. – Pᴇʜ Feb 23 '17 at 13:07
  • Are there only ever 4 lines in the file or could that change? Are you saying that you want the file to only contain the data between the quotation marks or if there lots more words you still only want the last two removed? – CLR Feb 23 '17 at 14:55

1 Answers1

1

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
Community
  • 1
  • 1
tretom
  • 559
  • 1
  • 7
  • 17
  • Thank you for your answer, i adapted your code to my probleme but it does nothing :( – babou Feb 23 '17 at 13:43
  • if your txt structure is exactly as it's in your post, then this code removes the last three words from the end of the lines. what you have to do is to save each newDataLine into a variable, and then to save everything into a file. – tretom Feb 23 '17 at 14:47