Results 1 to 4 of 4

Thread: Macro query

  1. #1
    5 Star Lounger
    Join Date
    Feb 2001
    Location
    Australia
    Posts
    676
    Thanks
    28
    Thanked 2 Times in 2 Posts

    Macro query

    I use the following macro to save a Word document as a plain text file.

    Sub SaveAsTxt()
    Dim strName As String
    strName = ActiveDocument.FullName
    strName = Left(strName, Len(strName) - 3) & "txt"
    ActiveDocument.SaveAs strName, wdFormatText
    End Sub

    This works as intended if the original is a .doc file (e.g., "Test.doc" is saved as "Test.txt") but not if the original is a .docx file (e.g., "Test.docx" is saved as "Test.dtxt"). How can I add a condition so that both .doc and .docx files are saved as .txt files?

  2. #2
    3 Star Lounger
    Join Date
    Feb 2001
    Location
    Willow Grove, Pennsylvania, USA
    Posts
    205
    Thanks
    4
    Thanked 49 Times in 40 Posts
    The old WordBasic from 20 years ago had some tricks that VBA still can't match. Fortunately, the WordBasic object in VBA still has those abilities (http://www.word.mvps.org/FAQs/Macros...icCommands.htm), one of which is the FilenameInfo function. This version of your macro doesn't care what the original extension of the file was:

    Code:
    Sub SaveAsTxt()
        Dim strName As String
        strName = ActiveDocument.FullName
        strName = WordBasic.FilenameInfo(strName, 5) & _
                  WordBasic.FilenameInfo(strName, 4) & _
                  ".txt"
        ActiveDocument.SaveAs strName, wdFormatText
    End Sub

  3. The Following User Says Thank You to jjfreedman For This Useful Post:

    Murgatroyd (2013-05-21)

  4. #3
    5 Star Lounger
    Join Date
    Feb 2001
    Location
    Australia
    Posts
    676
    Thanks
    28
    Thanked 2 Times in 2 Posts
    Thanks for your reply. That works fine.

  5. #4
    Super Moderator
    Join Date
    May 2002
    Location
    Canberra, Australian Capital Territory, Australia
    Posts
    5,054
    Thanks
    2
    Thanked 417 Times in 346 Posts
    Here's a better approach (IMHO):
    Code:
    Sub SaveAsTxt()
    Dim strName As String
    With ActiveDocument
        strName = .FullName
        strName = Left(strName, InStrRev(strName, ".")) & "txt"
        .SaveAs strName, wdFormatText
    End With
    End Sub
    Cheers,

    Paul Edstein
    [MS MVP - Word]

Posting Permissions

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