Consulting

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
    objFile.Close
    arrLines = Split(strContents, vbCrLf)
    Set objFile = objFSO.OpenTextFile("C:\Users\final\Desktop\wiki.txt", ForWriting)
    lines.RemoveAt (lines.Count - 1)
    objFile.WriteLine arrLines(i)

    objFile.Close


    End Sub

  2. #2
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    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)
      objFile.Close
      
      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)  'https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.remove?view=netcore-3.1
      objFile.WriteLine Join(a, vbCrLf)
      objFile.Close
      
      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
  •