PDA

View Full Version : Easy! Need some help, Delete Line from txt file



paolo.libero
09-21-2020, 11:19 AM
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

Kenneth Hobs
09-21-2020, 12:14 PM
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

paolo.libero
09-21-2020, 01:25 PM
Thank you so much, kenneth this worked great!