(Solved) – VBA question – rename text file based on first line of text come across

  • by
(solved)-–-vba-question-–-rename-text-file-based-on-first-line-of-text-come-across

I have a long list of text files (all different names.txt, but small files) and i want to rename them based on the first line of text found in the individual text files. However my problem is that some file have a few enters before the text and somme don’t. So when i use the code below (i am a newbie in coding) the text file with a few blank enters return with a (blanc).txt.

Sub RenameTextFile()

    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Dim fso, MyFile, FileName, TextLine

    Set fso = CreateObject("Scripting.FileSystemObject")

    Set fol = fso.getfolder("C:FolderPath")

    For Each fil In fol.Files

        FileName = fil

        Set MyFile = fso.OpenTextFile(FileName, ForReading)

        Do While MyFile.AtEndOfStream <> True

            TextLine = MyFile.ReadLine
            MyFile.Close

            fil.Name = TextLine & ".txt"
            Exit Do

        Loop

        MyFile.Close
    Next fil
End Sub

I hope someone can help me.

Leave a Reply

Your email address will not be published. Required fields are marked *