• A Loop Macro to Convert *.TXT to *.DOC or *.DOCX Files

    Home » Forums » AskWoody support » Productivity software by function » MS Word and word processing help » A Loop Macro to Convert *.TXT to *.DOC or *.DOCX Files

    Author
    Topic
    #495697

    Over the years I have collected a lot of recipes and saved them in the TXT format, thought it help to conserve hard drive space this way.

    Now, that I am wanting to make an ePub from them in order to have on my Ipad1 (old version like me) and be able to take with me into the kitchen, I have noticed that Calibre likes DOCX or HTML files. I tried opening each of the txt file in Word 2007 and then doing all of the formatting and then saving as a doc or docx file. But I just have to many recipes to do this each and every individual file. So I need help, is there a macro I can use to help this old man resolve this dilemma of mine?

    Here is the formatting in a macro I started with on with DOC files but do not know how to go from here and make it Loop through all of the files in the folder I use C:RecipesTxt2Doc

    Sub PageTxtFontHeader1()

    ‘ PageTxtFontHeader1 Macro


    With Selection.PageSetup
    .LineNumbering.Active = False
    .Orientation = wdOrientPortrait
    .TopMargin = InchesToPoints(0.6)
    .BottomMargin = InchesToPoints(0.6)
    .LeftMargin = InchesToPoints(0.6)
    .RightMargin = InchesToPoints(0.6)
    .Gutter = InchesToPoints(0)
    .HeaderDistance = InchesToPoints(0.5)
    .FooterDistance = InchesToPoints(0.5)
    .PageWidth = InchesToPoints(8.5)
    .PageHeight = InchesToPoints(11)
    .FirstPageTray = wdPrinterDefaultBin
    .OtherPagesTray = wdPrinterDefaultBin
    .SectionStart = wdSectionNewPage
    .OddAndEvenPagesHeaderFooter = False
    .DifferentFirstPageHeaderFooter = False
    .VerticalAlignment = wdAlignVerticalTop
    .SuppressEndnotes = False
    .MirrorMargins = False
    .TwoPagesOnOne = False
    .BookFoldPrinting = False
    .BookFoldRevPrinting = False
    .BookFoldPrintingSheets = 1
    .GutterPos = wdGutterPosLeft
    End With
    Selection.WholeStory
    Selection.Font.Name = “Times New Roman”
    Selection.Font.Size = 11
    Selection.MoveDown Unit:=wdLine, Count:=1
    Selection.HomeKey Unit:=wdStory
    Selection.Style = ActiveDocument.Styles(“Heading 1”)
    End Sub

    If anyone can help guide me I would greatly appreciate it.
    Thanks,
    The Old Man

    Viewing 5 reply threads
    Author
    Replies
    • #1460489

      It seems to me the most appropriate way to do this would be to combine all the recipe files into a single Word document, perhaps with a table of contents too, rather than creating a separate file for each one. That process can be automated, but I don’t want to go coding it before confirming that’s what you want to do.

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

      • #1460497

        It seems to me the most appropriate way to do this would be to combine all the recipe files into a single Word document, perhaps with a table of contents too, rather than creating a separate file for each one. That process can be automated, but I don’t want to go coding it before confirming that’s what you want to do.

        I do have my recipes stored in separate folders based upon the recipes like as follows, this folder alone has almost 800 recipes inside the folder named Crockpot[INDENT]
        Venison Meat
        Beans or Legumes
        Beef
        Breads
        Breakfast
        Casseroles
        Chicken
        Chili
        Deserts
        Drinks
        Fish
        Lamb
        Pastas
        Pork
        Soups
        Stews
        Turkey
        Vegetables[/INDENT]

        So yes I need something to Batch, Macro, Combine, and/or Merge somehow the contents of each individual folder and then I will try and make an ePub from just from that folder’s combined file..

        Are you saying there is a way to do this for the *.TXT, *.DOC and or *.DOCX files?

        Thanks Again in Advance,
        The Old Man

        • #1460508

          So yes I need something to Batch, Macro, Combine, and/or Merge somehow the contents of each individual folder and then I will try and make an ePub from just from that folder’s combined file..

          Are you saying there is a way to do this for the *.TXT, *.DOC and or *.DOCX files?

          Indeed I am. For example:

          Code:
          Sub GenerateRecipeDocument()
          Application.ScreenUpdating = False
          Dim strFolder As String, strFile As String, wdTgtDoc As Document, wdSrcDoc As Document, Rng As Range
          strFolder = GetFolder
          If strFolder = "" Then Exit Sub
          Set wdTgtDoc = Documents.Add
          With wdTgtDoc
            With .PageSetup
              .LineNumbering.Active = False
              .Orientation = wdOrientPortrait
              .TopMargin = InchesToPoints(0.6)
              .BottomMargin = InchesToPoints(0.6)
              .LeftMargin = InchesToPoints(0.6)
              .RightMargin = InchesToPoints(0.6)
              .Gutter = InchesToPoints(0)
              .HeaderDistance = InchesToPoints(0.5)
              .FooterDistance = InchesToPoints(0.5)
              .PageWidth = InchesToPoints(8.5)
              .PageHeight = InchesToPoints(11)
              .FirstPageTray = wdPrinterDefaultBin
              .OtherPagesTray = wdPrinterDefaultBin
              .SectionStart = wdSectionNewPage
              .OddAndEvenPagesHeaderFooter = False
              .DifferentFirstPageHeaderFooter = False
              .VerticalAlignment = wdAlignVerticalTop
              .SuppressEndnotes = False
              .MirrorMargins = False
              .TwoPagesOnOne = False
              .BookFoldPrinting = False
              .BookFoldRevPrinting = False
              .BookFoldPrintingSheets = 1
              .GutterPos = wdGutterPosLeft
            End With
            With .Styles("Normal").Font
              .Name = "Times New Roman"
              .Size = 11
            End With
            .Range.Style = "Normal"
            strFile = Dir(strFolder & "*.txt", vbNormal)
            While strFile  ""
              Set wdSrcDoc = Documents.Open(FileName:=strFolder & "" & strFile, AddToRecentFiles:=False, Visible:=False)
              With wdSrcDoc.Range
                Do While .Characters.Last.Previous.Text Like "[ " & vbTab & vbCr & Chr(12) & "]"
                  .Characters.Last.Previous.Text = vbNullString
                  If Len(.Text) = 1 Then Exit Do
                Loop
                Do While .Characters.First.Text Like "[ " & vbTab & vbCr & Chr(12) & "]"
                  If Len(.Text) = 1 Then Exit Do
                  .Characters.First.Text = vbNullString
                Loop
              End With
              .Sections.Add Range:=.Range.Characters.Last, Start:=wdSectionNewPage
              .Range.Characters.Last.Text = wdSrcDoc.Range.Text
              .Sections.Last.Range.Paragraphs.First.Style = "Heading 1"
              wdSrcDoc.Close SaveChanges:=True
              strFile = Dir()
            Wend
            If .Sections.Count > 1 Then
              With .Sections(2).Footers(wdHeaderFooterPrimary)
                .LinkToPrevious = False
                .Range.Fields.Add Range:=.Range, Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
                .Range.Paragraphs.First.Alignment = wdAlignParagraphCenter
                .PageNumbers.RestartNumberingAtSection = True
                .PageNumbers.StartingNumber = 1
              End With
            End If
            Set Rng = .Range(0, 0)
            Rng.Collapse wdCollapseStart
            .Range.Fields.Add Range:=Rng, Type:=wdFieldEmpty, Text:="TOC", PreserveFormatting:=False
          End With
          Set Rng = Nothing: Set wdSrcDoc = Nothing: Set wdTgtDoc = Nothing
          Application.ScreenUpdating = True
          End Sub
          
          Function GetFolder() As String
          Dim oFolder As Object
          GetFolder = ""
          Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
          If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
          Set oFolder = Nothing
          End Function

          Simply run the macro and point its browser to the folder you want to process.

          Note: The code could be simplified and a more developed front section employed if you created a ‘Recipe’ template with the desired page layout and formatting, rather than requiring the macro to apply it by brute force for each document.

          Cheers,
          Paul Edstein
          [Fmr MS MVP - Word]

    • #1460665

      Mr Paul Edstein,

      That macro was just amazing. I guess I am getting too old for these programing codes.

      I will create a Recipe Template right now.. How would I use this new template in reference to you macro, if you don’t mind?

      AND A GREAT BIG THANKS TO YOU SIR FOR THE WORK YOU DID!!

      How long have you been working with macros?

      Again Thanks,
      The Old Man

      • #1460666

        I was interrupted before I could run the macro, I have now tried to run it, but get a
        “Compile Error:
        Ambiguous name detected; GetFolder”

        And the macro stops on line with the following:

        Function GetFolder() As String

        Sorry I did not run it any sooner.
        The Old Man

    • #1460672

      How would I use this new template in reference to you macro, if you don’t mind?

      Basically, you’d create a one-page document with the desired page setup, including whatever you want as the standard content for that page, including a TOC (Table of Contents) field – ignoring the fact it wouldn’t have any content to reference. You then add the following simplified version of the macro to the document’s ‘ThisDocument’ module and save the document as a Word Template (.dot or .dotm file).

      Code:
      Sub Document_New()
      Application.ScreenUpdating = False
      Dim strFolder As String, strFile As String, wdTgtDoc As Document, wdSrcDoc As Document, Rng As Range
      strFolder = GetFolder
      If strFolder = "" Then Exit Sub
      Set wdTgtDoc = ActiveDocument
      With wdTgtDoc
        strFile = Dir(strFolder & "*.txt", vbNormal)
        While strFile  ""
          Set wdSrcDoc = Documents.Open(FileName:=strFolder & "" & strFile, AddToRecentFiles:=False, Visible:=False)
          With wdSrcDoc.Range
            Do While .Characters.Last.Previous.Text Like "[ " & vbTab & vbCr & Chr(12) & "]"
              .Characters.Last.Previous.Text = vbNullString
              If Len(.Text) = 1 Then Exit Do
            Loop
            Do While .Characters.First.Text Like "[ " & vbTab & vbCr & Chr(12) & "]"
              If Len(.Text) = 1 Then Exit Do
              .Characters.First.Text = vbNullString
            Loop
          End With
          .Sections.Add Range:=.Range.Characters.Last, Start:=wdSectionNewPage
          .Range.Characters.Last.Text = wdSrcDoc.Range.Text
          .Sections.Last.Range.Paragraphs.First.Style = "Heading 1"
          wdSrcDoc.Close SaveChanges:=True
          strFile = Dir()
        Wend
        If .Sections.Count > 1 Then
          With .Sections(2).Footers(wdHeaderFooterPrimary)
            .LinkToPrevious = False
            .Range.Fields.Add Range:=.Range, Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
            .Range.Paragraphs.First.Alignment = wdAlignParagraphCenter
            .PageNumbers.RestartNumberingAtSection = True
            .PageNumbers.StartingNumber = 1
          End With
        End If
        .TablesOfContents(1).Update
      End With
      Set Rng = Nothing: Set wdSrcDoc = Nothing: Set wdTgtDoc = Nothing
      Application.ScreenUpdating = True
      End Sub
      
      Function GetFolder() As String
      Dim oFolder As Object
      GetFolder = ""
      Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
      If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
      Set oFolder = Nothing
      End Function

      How long have you been working with macros?

      I’ve mainly been dabbling with them for the 6 years or so since I retired.

      “Compile Error:
      Ambiguous name detected; GetFolder”

      Suggests you have two copies of the GetFolder function in your code module.

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

    • #1461002

      My Friend Paul,

      I am sending this notice to let you and others know that due to an electrical storm, I no longer have any of my data files and your macros you made. I am currently reaching out to my friends as to the obtain their DVDs of the recipes I made for them so I can start over again.

      I had just obtain a 2TB external hard drive the other day, but had not got around to backing up my data from the computer, how dumb of me.

      I am trying to get another computer piece milled back into at least a minimal working condition for now, just for my wife sakes as I am using the wife’s computer right now and we all if the wife isn’t happy, no one is. hehehe.

      Anyway I really do appreciate your help and looking, hopefully, to start again. But this time with a back-up plan in place and a better understanding of macros but most importantly, I know now where to search and find answers concerning macros – here on this forum. What a place this is!

      “Data Saving Is The Future”, :clapping:
      The Old Man

      I will be back.

    • #1461025

      Depending on what happened, you may find the data are recoverable from your old HDD. All you may need to do is to use some file recovery software like Back2Life or, if the actual PC is damaged, install the old HDD into an external HDD case and plug the installed drive into a USB port in your new PC.

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

    • #1461159

      Paul,
      The hard drive is “Trashed”.
      I had pulled what I could from the computer and had placed it near the waste area, a safe area, I thought.
      On Sunday nights, we set out our trash cans for the Monday’s pickup and as usual the wife when she came into my office area and asked about the trash in the room. I thought she was talking about my waste basket.

      So awhile ago I went to connect the hard drive from the damage computer and could not find it. I knew where I had placed it, but that area was clean, there was nothing there. This is when I went, “Oh POOP!”

      I asked her if she had picked up anything near the waste basket and she sure enough she said, Don’t you remember, I asked you about all of these trashy looking pieces laying near the waste basket as to if they were trash or not? But you never looked up from the Ipad and said, Yes, it is ready to go the garbage container, so I took it all and place inside the the garage container.

      I said I had placed all of the computer parts that were not damaged right there next to the waste basket. Then she reminded me that as usual I was not paying attention to her and I had again, ‘Tuned Her Out’. (isn’t amazing as to how much they can remember?)

      To make matters worst, I was the one who rolled the container to the curb last night. Now the hard drive is “Trashed”. Let the old saying, “The wife happy, we happy.” But we need to add, “If We listen and understand what the wife said, so we don’t loose anything.”

      The Old Man.

    Viewing 5 reply threads
    Reply To: A Loop Macro to Convert *.TXT to *.DOC or *.DOCX Files

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: