PDA

View Full Version : Solved: Pls Help! Achieve IF Field through VBA code?



BonnyeLiz
03-09-2005, 10:59 AM
Newbie here with a major headache from :banghead: . I have searched and searched and I'm confident and hopeful that you fine folks can help me!

I'm trying to achieve a last page footer (unable to tell how long the doc will ultimately be) that is populated by a macro. I found the solution to achieving a last page only footer by using an IF field:

{ IF { PAGE} = { NUMPAGES} {FILENAME \p} }

Now how do I code the macro so that the filename within the IF field is populated by the macro results instead?

Here is my code so far - Any help at all is gratuitously appreciated at the maximum!


Sub AutoNew()

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect
End If

If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If

If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If

Selection.EndKey Unit:=wdStory
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

If Selection.HeaderFooter.IsHeader = True Then
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Else
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
End If

Selection.EndKey Unit:=wdLine
Selection.TypeParagraph
Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
caseno$ = WordBasic.[Left$](data_$, 10)
If caseno$ = "[{CASENO}]" Then
CASENO2$ = Mid(data_$, 11)
WordBasic.Insert CASENO2$
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Font.TimesNewRoman.Size = 7
End If
Wend
Close 1
Selection.MoveDown
Selection.TypeParagraph
Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
PATHANDFILENAME$ = WordBasic.[Left$](data_$, 19)
If PATHANDFILENAME$ = "[{PATHANDFILENAME}]" Then
PATHANDFILENAME2$ = Mid(data_$, 20)
' Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
' Selection.Font.Size = 9
End If
Wend
Close 1
WordBasic.Insert PATHANDFILENAME2$
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveDocument.ProtectionType = wdNoProtection _
Then ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End Sub


:help :bug:

Anne Troy
03-09-2005, 11:17 AM
Hi! If your code doesn't look quite right after posting, then just edit your post, select it all, and hit that AA button with the red X through it. That removes any formatting from pasting, and allows the VBA tags to work properly on it. :) Good luck, Bon!

fumei
03-09-2005, 12:30 PM
Footers are part of the Section - they do not exist on their own. Yes there, of course a last page, but it will be part of the Section that contains i8t.

A lot depends on whether your document is using multiple Sections, AND if you have those sections using Different first page, and/or Different Odd/Even.

Ther is definitely a way to do what you ask. Allow me to go through what I think you want.

Regardless of the number of pages, create a separate footer for the last page. Correct?

This can be done. However, a major question is: what do you want to happen if additional text is inserted into the document?

Additional text will increase the pages, and these pages will include the footer. If additional text will never be inserted, then the solution is fairly straightforward. If additional text may ever be inserted, and you do NOT want this footer to be on any other page than the LAST page, it will be a bit more tricky. Still possible though.

Footers are part of the Section - they do not exist on their own. Yes there, of course a last page, but it will be part of the Section that contains i8t.

A lot depends on whether your document is using multiple Sections, AND if you have those sections using Different first page, and/or Different Odd/Even.

Ther is definitely a way to do what you ask. Allow me to go through what I think you want.

Regardless of the number of pages, create a separate footer for the last page. Correct?

This can be done. However, a major question is: what do you want to happen if additional text is inserted into the document?

Additional text will increase the pages, and these pages will include the footer. If additional text will never be inserted, then the solution is fairly straightforward. If additional text may ever be inserted, and you do NOT want this footer to be on any other page than the LAST page, it will be a bit more tricky. Still possible though. The following is basic - not checking or covering if additional text is inserted. It simply makes a separate section for the last page, and puts a filename field in the footer.

What it does:

1. Go to the last page - whatever it is
2. Back up one page
3. Go forward one page (brings it to the top. Finer tuning could use the bookmark range of the last page to do the same, but it is more code and just looks fancy...I skipped it)
4. back up ONE character
5. Insert a section break.
6. EXPLICITLY make sure that this new section does not have different first page or different odd/even
7. sets a filename field in the footer.

Done.
Sub LastPageFooter()
'
Dim i As Integer
i = ActiveDocument.Sections.Count
Selection.EndKey Unit:=wdStory
Selection.GoTo What:=wdGoToPage, _
Which:=wdGoToPrevious, Count:=1, Name:=""
Selection.GoTo What:=wdGoToPage, _
Which:=wdGoToNext, Count:=1, Name:=""
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.InsertBreak Type:=wdSectionBreakNextPage
With Selection.PageSetup
.SectionStart = wdSectionNewPage
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
End With
With ActiveDocument.Sections(i + 1).Footers
.Item(1).Range.Fields.Add _
Range:=.Item(1).Range, _
Type:=wdFieldEmpty, _
Text:="FILENAME \p "
End With
End Sub

BonnyeLiz
03-09-2005, 12:38 PM
Hi Gerry!

Yes, additional text will most often be entered into the document. I've considered the bookmark part, as I think it would be easier to tell the macro to place the text at a bookmark in the last page footer. I have developed a similar code to that you offered as well, but I can't seem to link it to the text created by the macro and only to populate the footer of the page number that equals the number of pages.

I've gone the route of creating a new section on the last page of the document (NOT relating to any other header or footer that could be in place elsewhere in the doc) and inserting a bookmark for the text placement. The filename will actually be derived from the macro that runs in the code I initially posted. Have I confused you enough yet? LOL!

fumei
03-09-2005, 02:06 PM
Actually, there was some errors in the code I posted. here is the corrected code:
Sub LastPageFooter()

Dim i As Integer
i = ActiveDocument.Sections.Count
With Selection
.EndKey Unit:=wdStory
.GoTo What:=wdGoToPage, _
Which:=wdGoToPrevious, Count:=1, Name:=""
.GoTo What:=wdGoToPage, _
Which:=wdGoToNext, Count:=1, Name:=""
.MoveLeft Unit:=wdCharacter, Count:=1
.InsertBreak Type:=wdSectionBreakNextPage
.MoveRight Unit:=wdCharacter, Count:=2
With .PageSetup
.SectionStart = wdSectionNewPage
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
End With
End With
ActiveDocument.Sections(i + 1).Footers(1).Range.Select
Selection.HeaderFooter.LinkToPrevious = Not Selection.HeaderFooter. _
LinkToPrevious
With ActiveDocument.Sections(i + 1).Footers
.Item(1).Range.Fields.Add _
Range:=.Item(1).Range, _
Type:=wdFieldEmpty, _
Text:="FILENAME \p "
End With
End Sub

OK"

1. the filename part is incidental. It is either a string derived from the macro (it writes a new filename...whatever), or a field that picks up the filename. If you are using the Field, then it will be the current filename. If it is derived from the macro, you must set that file save before you have the field.

2. Conceptual, there is NO such thing as a "last page footer". There is no such beast. Footers are ONLY objects of the Section. They have no other home.

3. Every Section has three (3) footers, regardless of whether you explicitly set them, or not.

4. If you run ANY macro that creates a footer on the current last page - it will do that. But if ever afterwards, that page becomes NOT the last page (by inserting additional text). that fact is irrelevant to the footer. Footers are part of the Section.

5. A bookmark put into the last page footer will work, but again, if additional pages are added, it will NOT affect that bookmark. Bookmarks are range objects, and the range location will remain. Again, if that bookmark was inserted into the footer of page 30 (the last page of a 30 page document), and the footer field set, if you add 5 pages...that bookmark will still be on page 30.

All that being stated, it is still possible to do what you want. it requires a lot more code though.

My questions to you are:

a) why do need to do this?
b) is it worth the effort?

However, in case it is.

declare a public variable OnLastPage as boolean

in a sub:
check if there is a section break just before the last page
if True,
check the footer of that last section
for a bookmark LastPageBM
if true
check the contents and update field if needed
if false
check the contents
delete things if needed
call separate sub LastFooter
if false
search make for a previous section break
if found
check footer contents
if contents are field filename
go to section break, back up
delete section break
call lastfooter sub
if contents are NOT empty AND NOT field filename
**** you need decision here
if NOT found
call LastFooter


LastFooter = essentially the code I posted above.

TonyJollans
03-09-2005, 03:20 PM
Hi BonnyeLiz,

Welcome to VBAX!

Gerry is more expert than I in setting up the various footers in multiple sections and you would do well to follow what he says.

However, I have a couple of comments:

1. You seem to scan the same file twice which overcomplicates the code.

2. Don't use WordBasic except in the very occasional cases where it provides facilities not available any other way.

3. Your code is in an AutoNew Macro and only runs when a new document is created, so you are setting up all your footers before doing much else. At this point you don't know what else will be in the document. Will there ever be sections added? (A variety of formatting can add sections without you always realising it).

4. The good news! The field you first posted will, effectively, give you a last page footer if it is in the footer which happens to be on the last page; if it is in any other footer it will print nothing so perhaps Gerry, too, is overcomplicating things slightly. Code for adding nested fields is a little awkward but it can be done.

BonnyeLiz
03-10-2005, 07:27 AM
To answer your questions... It was discovered during my contract that I could bend MS Word to will by VBA code. Folks here have slowly (and still are) migrated/migrating from WordPerfect. When I came along and showed them how to do different forms using code to make it easier on the user, they were thrilled. Unfortunately, since the discovery that I could make some things "special" for them - they want more, and I have less time to make it so.

Until now, the filename macro has been good enough. It has posted to every page in the document, in the footer. When I created protected forms for this particular area with the same code snippets in place and moving the filename/number off the first page- they decided they wanted on the last page only.

Believe me, the last two weeks I have been banging my head about this have made me wonder if it was worth the effort. If these people were not of such strong importance to this particular organization, I probably wouldn't have placed such an extreme effort. But, let's just say it is governmental level higher ups that are asking me to do this.

I've hit another brainstorm on this too - after reading through your code, Gerry. Wouldn't it be simpler to install a macro button on users' toolbars that launches the code? I'm not sure I can get them to go for that, however. They've been so used to doing nothing and getting this footer. Currently their answer to my inquiries is "how about examples of each method you're suggesting?" Arrrrgh!

Reading Tony's post gives me some hope too! I have it running through the AutoNew because the document is based on a template. It's the only way that their 3rd party software can integrate properly. I don't expect any section additions from the users, as this is also a protected document.
So it IS possible to code in nested fields??? I have searched through the object library trying to find something there that would indicate this. Do you have an example of how I would code nested field insertion that you would be willing to share?

I'm so appreciative of all this help in so many ways. It's allowing me to step back and take on new perspectives as well. Thank you, thank you, thank you!

BonnyeLiz : pray2:

OK Gang - I am going to slap myself if it is this easy. Someone else just offered this suggestion:

"Assign the name to a document property for example the title and then insert the document property using insert field into the header/footer.

ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = ManualTitle$"

So I assign the macro output text to a document property and then simply insert the If Field in the footer designating the document property as the text to be inserted? Is this really going to work??? I'm going testing, gang - give me your thoughts in the meantime. I'll let you know what I discover!

Bonnye

TonyJollans
03-10-2005, 10:21 AM
Yes, Bonnye, using a Document Property should work and makes the coding easier :). You an just put all your Fooers as you want them in the Template without using code at all.

BonnyeLiz
03-15-2005, 06:32 AM
I tweaked it a little, and it did not test successfully :dunno

Is there something so very obvious here that I am just not able to see? I figured that since it is a protected document, I should still seek the footer in the code? Even with the Header/Footer code removed - what am I doing wrong???


Sub AutoNew()
Dim strCase As String
strCase = CASENO2$
Dim strPath As String
strPath = PATHANDFILENAME2$

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect
End If

If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If

If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If

Selection.EndKey Unit:=wdStory
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

If Selection.HeaderFooter.IsHeader = True Then
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Else
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
End If


Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
caseno$ = WordBasic.[Left$](data_$, 10)
If caseno$ = "[{CASENO}]" Then
CASENO2$ = Mid(data_$, 11)
WordBasic.Insert CASENO2$
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Font.Size = 7
End If
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = strCase
Wend
Close 1

Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
PATHANDFILENAME$ = WordBasic.[Left$](data_$, 19)
If PATHANDFILENAME$ = "[{PATHANDFILENAME}]" Then
PATHANDFILENAME2$ = Mid(data_$, 20)
End If
ActiveDocument.BuiltInDocumentProperties(wdCurrentFolderPath) = strPath
Wend
Close 1

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveDocument.ProtectionType = wdNoProtection _
Then ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End Sub


New eyes could possibly see my simple errors :::crossing fingers:::
Thanks so much for looking!
Bonnye

sandam
03-18-2005, 03:55 AM
What goes wrong? What sort of errors do you get? Which lines are highlighted when you click DEBUG?

BonnyeLiz
03-21-2005, 02:17 PM
I receive no errors when debugging. However, when I run the macro within the document, I get "runtime error 13 mismatch" once it reaches the following line:



End If
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = strCase
Wend
Close 1


Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
PATHANDFILENAME$ = WordBasic.[Left$](data_$, 19)
If PATHANDFILENAME$ = "[{PATHANDFILENAME}]" Then
PATHANDFILENAME2$ = Mid(data_$, 20)

End If
ActiveDocument.BuiltInDocumentProperties(wdCurrentFolderPath) = strPath
Wend
Close 1

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

If ActiveDocument.ProtectionType = wdNoProtection _
Then ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True

End Sub



I remain.... clueless :dunno

TonyJollans
03-21-2005, 04:20 PM
Hi Bonnye,

Sorry for not replying earlier. I was out last week and did have a look at this when I came back but couldn't make it work as I wanted so left it, intending to return. Anyway ...

I don't see why you should get a type mismatch setting the property but if we try and simplify it perhaps we can sort it out.

To begin with:

(a) Set the Title Property of the Template blank.
(b) Forget the second string you want to have in the Footer.

and then, in your template footer put the fields:

{ IF { PAGE } = { NUMPAGES } { DOCPROPERTY TITLE } }

(and set it to whatever font and size you want)

You do not, then, need to edit the footer in your code (actually it would be nice if you could but I couldn't make it work no matter what I tried) so a lot of the code can be removed, leaving ..

Sub AutoNew()
Dim strCase As String
strCase = caseno2$
Dim strPath As String
strPath = PATHANDFILENAME2$

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect
End If

Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
caseno$ = WordBasic.[Left$](data_$, 10)
If caseno$ = "[{CASENO}]" Then
caseno2$ = Mid(data_$, 11)
WordBasic.Insert caseno2$
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Font.Size = 7
End If
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = strCase
Wend
Close 1

If ActiveDocument.ProtectionType = wdNoProtection Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End If

End Sub

Now, the code at the beginning sets strCase to caseno2$. Is this a global variable? And if so, what value does it have? I suspect you don't want that line. Next you declare and set variable strPath which you don't use. Let's delete those three lines for now.

Next, removing protection. There's no point in having protection on in the template if the first thing you do when you create a document based on it, is to remove that protection so make sure protection is not on in the template and then we can remove this code as well.

Now the loop processing the file. Because you are now using a pre-formatted field in the footer you no longer need to insert and format the text, so that's more code can go!!

Lastly, for the moment, you set (or you try to set) the "Title" document property to the variable strCase. You'll remember we removed the line setting that variable at the top, so it is now uninitialised. What I think you want is the value read from the file which you have in variable caseno2$, so let's use that for now - and as you only want to do it once, let's move it inside the IF block.

What is now left is this:

Sub AutoNew()
Dim strCase As String

Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
caseno$ = WordBasic.[Left$](data_$, 10)
If caseno$ = "[{CASENO}]" Then
caseno2$ = Mid(data_$, 11)
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = caseno2$
End If
Wend
Close 1

If ActiveDocument.ProtectionType = wdNoProtection Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End If

End Sub

Now we can begin to see the light! Although there's nothing wrong with using them, the variables caseno$ and caseno2$ don't really add anything as each is only used once so, for now at least, lets replace them with substring functions and, while we're at it let's get rid of the archaic WordBasic stuff - and also the redundant declaration of strCase. What's left? Well, this:

Sub AutoNew()

Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
If Left$(data_$,10) = "[{CASENO}]" Then
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = Mid$(data_$, 11)
End If
Wend
Close 1

If ActiveDocument.ProtectionType = wdNoProtection Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End If

End Sub

Now I have one problem (as I hinted near the beginning of this ramble) - I don't seem to be able to make the field update from the autonew macro and you won't be able to do it manually if the document is protected, so just for testing, can you comment out the setting of protection at the end of the code, like this:

Sub AutoNew()

Open "C:\cycomdat\lh_macro.txt" For Input As 1
While Not EOF(1)
Line Input #1, data_$
If Left$(data_$,10) = "[{CASENO}]" Then
ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle) = Mid$(data_$, 11)
End If
Wend
Close 1

'If ActiveDocument.ProtectionType = wdNoProtection Then
'ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
'End If

End Sub

Try running this. It will not actually show the value you want in the last page footer right away but you can manually fix that for now by switching into Print Layout View and back to Normal View (or vice-versa depending on where you start). And then switch on your Form protection.

If that works, we can build on it. if not we should be able to easily isolate the problem. If you've managed to read this far you have dedication if nothing else :)

BonnyeLiz
03-22-2005, 05:53 AM
:hi: Hi Tony,

I'll give this a try today and let you know! I appreciate you walking me through the changes step by step - that really helps me a lot! The code has been changed so many times since the start it is so helpful having another pair of eyes take a look at it. I'll be back to let you know what happens with it later today!

My profound thanks to you!
Bonnye

BonnyeLiz
03-22-2005, 08:59 AM
Still nothing. When I run the code, nothing populates where the "IF" field is located in the footer. When I ran a preliminary variation of the code in your reply, I ended up with the IF field being populated "Error! No bookmark defined."

I placed the IF field: {IF {PAGE} = {NUMPAGES} {DOCPROPERTYTITLE}
in the footer accordingly. I assured that the document property title was also blank, as you mentioned.

So why is it that the document property title field is not retaining the variable the code gives it?

:think:

Still dedicated to solving this mystery!
Bonnye

TonyJollans
03-22-2005, 09:13 AM
Hi Bonnye,

First, to see if the property is set:

After running your code on a new document, check the title via File > Properties > Summary tab

If it is set, then the field isn't picking it up so double check the field, make sure you've entered it correctly - I know you can't easily cut and paste it to here but what you've typed is invalid.

Let me know. Meanwhile I'll try and mock up a template and post it for you.

BonnyeLiz
03-22-2005, 09:25 AM
Hi Tony,

LOL - I am in the midst of doing the same - making a mock template with simpler variable determination to the "title" property. One that doesn't call the external information, just so I can try to make the text I want to appear as the property title. We shall see!

I went back to the properties of a new document after running the code, and the title still shows blank under the summary tab.

I'm not certain it matters, but the code that calls the caseno2$ information is affiliated with a third party software that assigns file numbers as part of case management. That's all it is, but it is not a variable that can be plucked from Word itself.

Still charging at it like a bull ~
Bonnye

TonyJollans
03-22-2005, 10:13 AM
Hi Bonnye,

Not sure about the third party product - are you actually interfacing to it in the process of creating a new document other than by reading the file?

Anyway, here's a basic template which creates a basic footer.

[EDIT}
Just re-read your post and if the title is blank, are you sure there is valid data in your text file?
[/EDIT]

BonnyeLiz
04-11-2005, 06:08 AM
I appreciate all of the assistance and efforts from all of you! I have finally moved away from this. Regardless of everything I've/We've attempted, it just isn't working. The timeline is too critical to fight with this method any longer, I'm afraid.

I've convinced them to simply allow the information on the second and subsequent pages in lieu of the final page of the document alone. I suggested a macro button assigned to their toolbars as well. They seem to be moving away from the document protection as well, which should make implementation of certain manuevers a bit easier.

Again, I applaud you all for being so helpful and allowing me to pick your brains! Until my next VBA/Word crisis, I remain...

Appreciative,
Bonnye :bow:

fumei
04-13-2005, 09:28 AM
I have been away...could you please state the needs requirement again?

If I understand it:
1. to have a separate footer for WHATEVER is going to be the last page.;
2. to adjust (that is, remove) any PREVIOUS last page footer, if any change in text content changes what is the last page.

If this is correct, please confirm requirements, because I believe there is a relatively simple way to do this.

BonnyeLiz
04-13-2005, 09:38 AM
Hi Gerry,

There is a Word document that needs a footer on the last page ONLY which needs to include a File number (created by Third Party Software) that is generated by a macro within the document. The filename and path are easily generated by using the IF field inserted to only appear of the page number equals the numbr of pages. There is no certainty of how many pages long the document will be.

The last attempt made was to assign the value created by the macro (filenumber from third party software) to a property within word, and then use the same IF field code to generate the information. I was never able to get that to work successfully.

If you have any other suggestions, they are most certainly welcomed!

Bonnye

fumei
04-13-2005, 12:18 PM
OK, let me see if I understand correctly.

You need a single macro that both gets a string from someplace else, AND inserts it into the last page ONLY.

It is that last page ONLY that can be the problem. As I previously posted, there are three footers in each section. Say you have NO section breaks, and you have code that displays the text of each footer in that section. Even though you think you have only one footer, you will get THREE messages, because there are always three footers in every section.

If the requirement is to have it ONLY on the last page, there is no way around this issue. You must make the last page a separate section.

This problem would not be a problem at all if there is not a requirement for the footer to be on the last page ONLY.

Just to demonstrate. say you have a document, five pages long. You make no adjustments to page setup. No different odd/even, no different first page. You put into the footer the text "whatever it is".

If you run code that checks the text of each footer in the section and performs an InStr to see if the footer text contains "whatever". It displays a messagebox with the result, AND the index number of the footer.

You will get THREE message boxes. The first will be 11 - the first 1 indicating the position of the searched for string. "whatever" is at position 1 of "whatever it is". The second 1 is the index of the footer.

The second message will be 02. The 0 is the result of the search. It returns a 0 because the second footer text does NOT contain the searched for string. The second footer does NOT have any text at all.

The third message box will be 03 - for similar reasons.

This is very important, because if you look at the document, there is footer text on EVERY page. However, technically, the second footer object in the Section has NO text, as does the third footer object.

So. If the requirement is it must be on the last page ONLY, and the number of pages can change (and that seems to be a given), you MUST search back through all the footer objects for something that identifies a previous inserted filename.

I am confused with post that refer to templates, and AutoNew routines.

PLEASE - spec out exactly what you want to happen.

Is this a new document?
Is this a previous saved document that may get a new filenumber, and therefore will be saved as a new filename?
Does it have to be on the last page?

As much as Tony may think I possibly make things too complicated (and he is absolutely correct in that sometimes), if the requirement is for:

1. the search for, and removal of, a previous footer containing an old filename;
2. a RE-Sectioning to maintain a separate footer for ONLY the last page;

Then it IS complicated. Do-able, but complicated.

Just to be clear, if you have a IF field in a footer, and you add 20 pages, that if field is still back there - especially if there are new sections.

So what I need to know is:

Is this for a template that will be making a new document, getting a new filename filenumber, and putting it into the last page footer...and is a ONE SHOT DEAL;

OR, is this a document that may change;

OR is the first, but ALSO may change.

Talk to me. I think this can be done. However....uh, you have two days. I fly out early Saturday, and will be mostly unavailable for two weeks. Doing a photo shoot in the redwoods of Northern California. Mmmmmm, yum, cool, fog, and wet.

MOS MASTER
04-13-2005, 12:41 PM
Hi Gerry, :D

Also had a think about the subject.
Indead it seams like an interessting task to do this by code.

For me the big questione is when to execute the code..
This talk about eventhandlers that start at creating ore opening a document didn't get me closer to the sollution.. (Users can still do a lot to change the outcome afterwards)

If the procedure had be executed on a print event or on a save event then I think it would be much easier...(For the basic reason that you don't have to worry about al that extra pages a user could possibly create)

But I was wondering bonny?
The sample Tony made for you...what didn't work quite right for you?

I've been playing with it and it seams to work well? (What am I missing) :dunno

Gerry...did you look at Tony's example? Did you find anything not working there...It still seams a simple ellegant sollution.

When adding pages to the example the footer shifts nicely so...I thought that had to do it for Bonny...

BonnyeLiz
04-14-2005, 07:36 AM
The sample that Tony provided worked wonderfully :thumb during my testing of it as well... UNTIL I tried to run it through with the third party software. The field showed nothing - just blank.

When using other text, it worked. I even tested the macro alone to assure that accurate data was being passed through to the document. Without the field, it places the file number in the footer. When I applied the sample, blank.

I don't understand it either, and couldn't see wasting anymore of Tony's time on it, as he was so kind and helpful. :bow: I have to assume that it has something to do with the parameters involved in the third party software. I never received an error running the code using the third party macro, but no data was produced in the document either.

The office the project is for seems to be happy with another template that is no longer protected, and inserts the file number at remaining pages after page one.

Finally admitting to being stumped, I just implemented the next best and most plausible idea for them. I KNOW that this would work if it weren't for the data needing to come from this third party software!

Bowing to all of your greatness~
Bonnye

TonyJollans
04-14-2005, 08:41 AM
Hi Bonnye,

The source of your data as far as Word is concerned appears to be a text file. That text file may have been created by a third party app but that shouldn't make any difference. I'm afraid I'm at a loss at the moment to further explain what the problem may be although I'm happy to carry on looking at it if you want me too - and I'm sure others here are too.

MOS MASTER
04-14-2005, 11:21 AM
The sample that Tony provided worked wonderfully :thumb during my testing of it as well... UNTIL I tried to run it through with the third party software. The field showed nothing - just blank.
Hi, :D

Ah ok...really thought I was losing my mind figuring out what could be wrong with the thing..

Like Tony says: Is the Third party app only providing the txt file or is it also automating this particuler template? If no automation is done by that app It shure seams strange that it's not working.

Off course it's also possible that this is an version related problem. Perhaps you can provide us with the destination version off Word the end users are running. (97,2000,2002 or 2003?)

I'd like to test it aswell in that specific version off Word.

To be precise on what to test are you using the same sample as Tony's example?

See Yah! :thumb
Ps..happy for you the customer is satisfied with the alternative..

fumei
05-02-2005, 12:31 AM
OK. I was away again. Right now I am on a friend's computer, but I will be in the office tomorrow (Monday). I have a complete solution for you.

It does not use docvariables

It makes NO difference the current situation. It does:

check the cause of the last page = is it a page Break, a Section break or just pushed over into a new page by text.

It removes all existing footers that contain the document path and filename.

It forces the last page, and ONLY the last page to have a footer with the document name and path. It does not use any flelds, or an IF test.

You can add as much text as you like., anywhere. You can remove any text anywhere. Run the code and it always fixes it that the last page has the correct footer. Regardless of existing situation. Works perfectly. I will post in a few hours. need to try and get SOME nap.

fumei
05-02-2005, 06:34 AM
Here is a solution that can be adjusted to accepted any string to be placed in the footer of the LAST page, and ONLY the last page. It is fully error trapped to make any adjustments for movement of the last page. Adding text to make a new last page is fully taken care of.

It does not use any IF fields, docvariables, or any other fields.

What it does:

1. goes to the last page.
2. set the Selection.SetRange to the VERY LAST character, just before the start of the last page.
3. performs tests on the next character.
LOGIC: the last page can BE the last page for three reasons.
a) an explicit Section break
b) an explicit page break
c) a DERIVED page - that is, it is calculated by Word because the text simply went on past the end of the previous page.

4. a) if there is a section break, then the last page is already in its own section;
4. b) if there is a page break (using a Ctrl-Enter) move forward and make a section break, move back and delete the page break; 4. c) if there is not a break, insert a section break

5. perform check of all footers searching for the string. If found, delete all footers with that string. All other footer text is ignored. This could be adjusted if you state requirements to do so.

The string is, in the attached file, the document path and file name - using ActiveDocument.FullName. This can be easily adjusted to pick up whatever you want. If you have a routine that determines the string by a third party, that is OK, as long as you get a string. You could save the file with a SaveAs, then use the attached document code to simply use the filename.

6. insert the document fullname (path and filename) into the footer of the last page.

As stated, to maintain ONLY the last page having the footer, you MUST make the last page into its own section. This does. I have it running on Document_Close so you can add, delete what you want. Put 400 pages after the previous last page - don't matter. It will make whatever is the last page (and ONLY the last page) have its own footer with the document path and filename in it.

The document attached is currently empty of text. Test it out. The code is commented fairly well, so you should have no problem figuring it out. It could easily be adjusted to take an input string for whatever you want to go into the footer. It is set, right now for path and filename.

Please let me know if you have further requirements that you have not stated.

could help if I attached the file, wouldn't it?

BonnyeLiz
05-02-2005, 07:38 AM
Wow! I'll test this out against the third party software that inserts the information. My sincerest thanks to you! :bow:

I'll let you know how it goes!

Bonnye

MOS MASTER
05-03-2005, 12:13 PM
Hi Gerry, :D

Nice clear coding works well!

But I still find it strange that Tony's example didn't work...it works over here...(Glad to the field feature was also nice) Oh well...can't understand everything...:dunno

fumei
05-04-2005, 10:35 AM
Hi Joost!

Actually Tony's example should work, at least generically. Although his example did not do the conditional checking for the last page generation. The only thing really different (other than that checking) is that mine will take any string. That being said, mine does not truly deal with the third party factor either. I am still unclear how that works. But, as long as you can get a string out of it, the code will do what appears to be the requirement.

Thanks for the compliment. Much appreciated.

MOS MASTER
05-04-2005, 01:53 PM
Hi Gerry, :D

Ah ok..thought I was losing my mind there.
I'm with a friend on a telephone line (Stone age) :rofl: now so I'll keep it brief..

As I recall (no time to test) Tony's example worked live meaning if you added a page the last header would still be the only one being filled..(But like I said the topic's been out off my head for a week so..)

Will test more tommorow!

And for your work:....this is always clearly explained/well motivated and most important easy to read! (That's what I like...readable Code)

Talk to yah....:whistle:

fumei
05-05-2005, 11:12 AM
We all secretly like readable code. Most of us are too lazy to write it. Although....Tony is a master, and I unabashedly bow in his direction. Ok, maybe not as commented as I like, but even masters have their quirks.

The reason I like clear readable code is...I had to figure out over 100,000 lines of jumbled, uncommented code once (COBOL). It literally gave me nightmares.

BTW: I think there may be an error in the file I uploaded. Not sure, and I have not had the time to check. There may be an incorrect return on one of the functions, depending on what is causes the last page to BE the last page.

MOS MASTER
05-05-2005, 11:22 AM
We all secretly like readable code. Most of us are too lazy to write it. Although....Tony is a master, and I unabashedly bow in his direction. Ok, maybe not as commented as I like, but even masters have their quirks.

The reason I like clear readable code is...I had to figure out over 100,000 lines of jumbled, uncommented code once (COBOL). It literally gave me nightmares.

Ah glad we like the same thing!

I to have had a simular encounter (to many times) with someones code who was very fond of not declaring variables and to make things worse liked 1 letter variables like: X = bla, y = bla, etc...(A Nightmare if the code is long and no comments are present)

After doing that my coding got a lot better from looking at it from another person's point of view (I'll let someone else decide if my code is ok or not) :rofl:

As a matter off fact I do like Sir Tony's code as much as you do!



BTW: I think there may be an error in the file I uploaded. Not sure, and I have not had the time to check. There may be an incorrect return on one of the functions, depending on what is causes the last page to BE the last page.
Ah..this could be had a quick spin at it and have not run it through the debugger...(worked well as I recall and like I said love the coding)

If the OP has problems with it there's time enough to fix it! :thumb

fumei
05-05-2005, 11:30 AM
Undeclared variables.....a curse. Hate them. Pure laziness as far as I am concerned. Or a arrogance of one's memory ability, or perhaps an total un-empathetic understanding that someone else is not a mind reader.

Mind you this was in the days when we did not have the luxury of using nice, long, fully named variables. So yes, lots of "x". The worst was using the SAME variable name in different procedures, but for DIFFERENT data types.

i As Integer is pretty common - still do it myself. A habit. But these guys sometimes used i As String....?????? Can we say consistent?

MOS MASTER
05-05-2005, 11:39 AM
A big Amen to you're comments....(and i do use a simple i for a counter also from time to time or an l if it needs to be long) :think:

But normally when I review codes I change to naming conventions and change to: lCnt or iCnt (Or for those who are in to 3 ltr prefixes: lngCnt or intCnt)

Cheers! ;)

TonyJollans
05-06-2005, 04:30 AM
Gerry, Joost,

Thankyou for the kind words about my coding. You are both excellent coders and praise from you is praise indeed.

It is probably true that my code sometimes lacks sufficient comments - I will try and do better :)

To take the thread off topic for a moment - it's funny you should mention Cobol, Gerry, - my son who is a web developer is amused by the fact, as he sees it, that my HTML looks like Cobol - I wonder if my VBA does too! Just for fun (well, there was a serious point to it) I once wrote a C program which looked exactly like Cobol - I forget the details now but I defined Cobol keywords as C elements (#define Identification Function Main(), etc. - or something of the sort) and if memory serves I couldn't quite get the same source to do the same thing run through the two different compilers but it was very close.

MOS MASTER
05-06-2005, 04:35 AM
Gerry, Joost,

Thankyou for the kind words about my coding. You are both excellent coders and praise from you is praise indeed.

It is probably true that my code sometimes lacks sufficient comments - I will try and do better :)

You're welcome Tony, :D

As for the lacks of sufficient comments I think we all fit that glove!
I hope I will get to the stage of always writing comments in my code (and hopefully more good habbits) even when replying to questions (in those small codes I usually forget it)

I'll leave the Cobol bith to Gerry...I know what it is, but that says it all! :rofl:

fumei
05-06-2005, 07:11 AM
Ah...back when in the days when that kind of stuff was what we did for fun!

MOS MASTER
05-07-2005, 11:01 AM
Ah...back when in the days when that kind of stuff was what we did for fun!
haha...yes time for tinkering seams less and less, but when it's there it's still so much fun! :rofl:

BonnyeLiz
05-25-2005, 06:15 AM
OK - Let's mark this solved! All the hardwork and dedication paid off tremendously and for ALL of your efforts, I am gracious :thumb

Until next time!
Bonnye

MOS MASTER
05-25-2005, 10:22 AM
Glad we could help! :friends: