Results 1 to 3 of 3

Thread: Easy! Need some help, Delete Line from txt file

  1. #1

    Easy! Need some help, Delete Line from txt file

    Hi to all, i'm a newbie into VBA coding, and i'm unexperienced, i'd be really glad and i'd appreciate if someone could help me,

    I'm creating a Vba that should open a txt file, read it and write it back excluding the last line (since apparently there's no way to delete directly last line)

    i'll past what i'm using, i keep having a run time error, and also an error that asks me to define the object, am i missing something?

    Sub Deletes_Last_Line()
    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set objFile = objFSO.OpenTextFile("C:\Users\final\Desktop\wiki.txt", ForReading)
    strContents = objFile.ReadAll
    arrLines = Split(strContents, vbCrLf)
    Set objFile = objFSO.OpenTextFile("C:\Users\final\Desktop\wiki.txt", ForWriting)
    lines.RemoveAt (lines.Count - 1)
    objFile.WriteLine arrLines(i)


    End Sub

  2. #2
    VBAX Guru Kenneth Hobs's Avatar
    Nov 2005
    Tecumseh, OK
    Welcome to the forum! Be sure to add the reference as commented. I used early binding. That let's intellisense work for those objects.

    You can delete the line that I commented with the .net reference to its collection object.

    Sub Deletes_Last_Line()  
      'Dim objFSO As Object, objFile As Object  'Late Binding
      Dim objFSO As FileSystemObject, objFile As TextStream 'Early Binding, Add Reference: Microsoft Scripting Runtime
      Dim a As Variant
      Const ForReading = 1
      Const ForWriting = 2
      'Set objFSO = CreateObject(“Scripting.FileSystemObject”)
      Set objFSO = New FileSystemObject
      Set objFile = objFSo.OpenTextFile("C:\Users\final\Desktop\wiki.txt", ForReading, True)
      a = Split(objFile.ReadAll, vbCrLf)
      ReDim Preserve a(LBound(a) To UBound(a) - 1)
      Set objFile = objFSO.OpenTextFile("C:\Users\final\Desktop\wiki.txt", ForWriting, True)
      'Lines.RemoveAt (Lines.Count - 1)  '
      objFile.WriteLine Join(a, vbCrLf)
      Set objFile = Nothing
      Set objFSO = Nothing
    End Sub

  3. #3
    Thank you so much, kenneth this worked great!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts