PDA

View Full Version : Construct filename from a specific word in document



Phil Smith
07-17-2010, 10:36 AM
Hi everyone.

This is my first post here, so here goes!

I am using Word 2007 and have a long document that I am going to split into separate documents, each consisting of a single page, using VBA that I found on this site.

As I found when trying to post this, you need to have a post count of 5 or greater to be able to post a link. Therefore, so you know the code I am intending to use, the code was submitted by Graham Skan and the post title was "Split document into multiple single-paged documents".

What I would like to do is adapt this code so that the filename used is an extracted word from each document.

Here are the details...

Each document follows the same layout and the "word" I wish to use for the filename is actually a number that is the 6th "word" from the start of the document.

As further information for you, the number also always follows the same characters every time, these being "LTP MB" where the space between "LTP" and "MB" is one press of the TAB key.

Firstly, can this be accomplished, and if so, do you need any more details?

Thanks in advance!

Phil

Tinbendr
07-17-2010, 12:45 PM
Welcome to VBA Express!

Is it ALWAYS the sixth word?

strNewFileName = docSingle.Range.Words(6) & ".doc"
If not, then you may have to search using the letters.

NOT TESTED
Move Dims to beginning.
Place after
'build a new sequentially-numbered file name Dim A$
Dim Rng As Range

Set Rng = docSingle.Range
With Rng
.Find.Execute findtext:="LTP" & Chr(9) & "MB", Forward:=True
If .Find.Found Then
.Collapse Direction:=wdCollapseStart
'Move to next Word
.Move wdWord
strNewFileName = Rng
Else
A$ = InputBox("Please enter a filename without extension")
If A$ <> "" Then
strNewFileName = A$ & ".doc"
End If
End If
set Rng = Nothing
end with

Phil Smith
07-18-2010, 01:51 AM
Thanks for the reply.

Turns out it was not the 6th word as it was saving everything as "LTP". I changed it to Words(8) and the filename was "MB", so I took a guess at Words(10) and all the documents were saved as I wanted.

However....

All the original formatting was lost in the new single page documents. Is there any way of preserving that when the new document is saved?

Regards,

Phil

Phil Smith
07-18-2010, 06:20 AM
:bump:
:anyone:

Anyone know if the formatting can be preserved when the individual single page documents are saved?

Phil

Tinbendr
07-18-2010, 01:35 PM
Try ActiveDocument.Range.FormattedText.Paste 'paste the clipboard contents to the new document

fumei
07-19-2010, 10:17 AM
Are the format that way because of Styles?