Solved

Debug VBA/Word macro

Posted on 2000-03-14
23
808 Views
Last Modified: 2008-03-04
What is wrong with this macro ?

Sub PrintPagesWithCodeword()

'Prints all pages with a given string

    Dim Message As String, Title As String, Default As String, SpecialCode As String
       
    Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
    Title = "PrintPagesWithCodeword"
    Default = "XYZ"   ' Set default, is set as case sensitive below.
    SpecialCode = InputBox(Message, Title, Default)
       
    Selection.HomeKey Unit:=wdStory  'start at the beginning
    With ActiveDocument.Content.Find
       Do While .Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True
          Selection.Find.Execute
          Application.PrintOut Range:=wdPrintCurrentPage
       Loop
    End With

End Sub


Background:

Original question was
xxxxx
Q.10306791 "Can I extract pages to print ? (WORD)".

I am getting very long documents by mail (under  "*.doc" format).  Within these numerous pages, I would like to print ONLY the pages beginning by a special code (let us say "XYZ").  Is this possible under MSWord 97 ?
xxxxx

I made a macro, tested and posted it. ACS accepted my comment before making a test run. After two modifications by me, each with what I thought sucessful printouts, it still does not run properly, instead of the pages with XYZ the first page is printed as many times XYZ is found (I must have been daydreaming, now, in a fresh doc, the sames happens on my PC)

Please fix this. It should be mentioned that ACS

a) Has tried the macro on both French OS + English MSOffice97 -SR2 and French OS and MSOffice97 -SR2.  Also on Dutch OS and MSOffice97 -SR2.

b) He viewed document on "normal", "page layout", tried to print and got no difference (only first page printed).

c) Has launched the macro from toolbar, from special made toolbar (a button linked to the macro), from within the VB menu ... and got no difference.

d) Although I do not think it is a language support problem, I am including AC's french formulation of the question "Je recois de longs documents en format doc (MSWord) dont je ne desire imprimer qu'un certain nombre de pages marquees par un symbole "XYZ".  Avez-vous idee comment on peut faire?".  
0
Comment
Question by:cri
  • 5
  • 5
  • 5
  • +3
23 Comments
 
LVL 4

Accepted Solution

by:
wesleystewart earned 100 total points
ID: 2617565
When you execute the line:

Application.PrintOut Range:=wdPrintCurrentPage

You should be printing the current page, but maybe executing Find.Execute twice is bugging it up somehow.  Did you try:

Do While .Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True

          Application.PrintOut Range:=wdPrintCurrentPage
       Loop

Wes
0
 
LVL 13

Author Comment

by:cri
ID: 2617807
You mean

    Do While Selection.Find.Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True

i.e. w/o the "With" instruction ?

0
 
LVL 17

Expert Comment

by:calacuccia
ID: 2618061
Hi Cri,

I think the problem is that you are not executing the Find command corectly. When testing if the Find.Execute result is true (so if something matching is find), you state in the following line:
   Selection.Find.Execute
Without any specification about what and how to execute the 'Find' Command.

I think this macro should work better (but haven't been able to test it because no printer at home - I saw that with the modified macro the selection actually scrolled through the matches in the document, opposed to the original macro). Here you go:

Sub PrintPagesWithCodeword()

'Prints all pages with a given string

    Dim Message As String, Title As String, Default As String, SpecialCode As String
       
    Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
    Title = "PrintPagesWithCodeword"
    Default = "XYZ"   ' Set default, is set as case sensitive below.
    SpecialCode = InputBox(Message, Title, Default)
       
    Selection.HomeKey Unit:=wdStory  'start at the beginning
    With ActiveDocument.Content.Find
       Do While .Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True
          Selection.Find.Execute FindText:=SpecialCode, Forward:=True, MatchCase:=True
          Application.PrintOut Range:=wdPrintCurrentPage
       Loop
    End With

End Sub

Hope this helps

Calacuccia
0
 
LVL 13

Author Comment

by:cri
ID: 2618651
calacuccia: Thanks, but the barebones "Selection.Find.Execute" is what Word records when you do it by hand. I think wesleystewart got it, but I want to test throughly, using 4 releases to get it working is worse than Microsoft...
0
 
LVL 5

Expert Comment

by:vboukhar
ID: 2618720
Hi, cri
Would you look at my approach? I change selection after each Find operation (BTW, I've added some code to avoid multiple printing of the same page, if few instances of SpecialCode are at the same page.
Sub PrintPages()

'Prints all pages with a given string

    Dim Message As String, Title As String, Default As String, SpecialCode As String
    Dim pageNum() As Long, k As Long, curPage As Long
    k = 1
    ReDim pageNum(k)
    Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
    Title = "PrintPagesWithCodeword"
    Default = "ÒÉÓË"   ' Set default, is set as case sensitive below.
    SpecialCode = InputBox(Message, Title, Default)
    Selection.HomeKey Unit:=wdStory  'start at the beginning
    flag = True
    Do While flag
          flag = Selection.Find.Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True)
          If flag Then
           Selection.Select
           curPage = Selection.Information(wdActiveEndPageNumber)
           already = False
           For i = 0 To UBound(pageNum)
            If pageNum(i) = curPage Then
              already = True
              Exit For
            End If
           Next i
           If Not already Then
             ReDim Preserve pageNum(k + 1)
             pageNum(k) = curPage
             MsgBox curPage
             ' comment line above and remove comment below to print pages
             'Application.PrintOut Range:=wdPrintCurrentPage
           End If
           Selection.Range.EndOf wdStory, wdExtend
          End If
    Loop
End Sub

It shows only page numbers instead of printing for debugging
Good luck!
0
 
LVL 5

Expert Comment

by:TigerMan
ID: 2618898
cri,

Tested and runs:

    Dim Message As String, Title As String, Default As String, SpecialCode As String
       
    Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
    Title = "PrintPagesWithCodeword"
    Default = "XYZ"   ' Set default, is set as case sensitive below.
    SpecialCode = InputBox(Message, Title, Default)
       
    Selection.HomeKey Unit:=wdStory  'start at the beginning
    With ActiveDocument.Content.Find
       Do While Selection.Find.Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True
          ' Selection.Find.Execute
          Application.PrintOut Range:=wdPrintCurrentPage
       Loop
    End With


Explanation?  Beats me - I am not overly familiar with Word VB.  I achieved success largely by trial/error with the suggestions posted.  If this works for you, you should probably give the points to someone else.

Dave
0
 
LVL 22

Expert Comment

by:ture
ID: 2618931
Cri,

A few things...

1. Use Selection.Find to search from the current selection and forward.
2. In your code, you executed the Find twice, as WesleyStewart pointed out.
3. Use .Found to determine if the text has been found or not.
4. You should make sure that the same page is not printed more than once, even if it contains more than one instance of the SpecialCode text.

Here is my modified version of your code:

Sub PrintPagesWithCodeword()
  'Prints all pages with a given string
 
  'Declare variables
  Dim Message As String
  Dim Title As String
  Dim Default As String
  Dim SpecialCode As String
  Dim LastPrintedPage As Long
 
  'Read SpecialCode from user
  Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
  Title = "PrintPagesWithCodeword"
  Default = "XYZ"
  SpecialCode = InputBox(Message, Title, Default)
 
  'Move selection to beginning of document
  Selection.HomeKey Unit:=wdStory
 
  'Set parameters for Find
  With Selection.Find
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = True
    .MatchAllWordForms = False
    .MatchFuzzy = False
    .MatchSoundsLike = False
    .MatchWholeWord = True
    .MatchWildcards = False
  End With
 
  'Loop through text until no more texts are found
  Do
    'Find next text
    Selection.Find.Execute FindText:=SpecialCode
   
    'If text is found...
    If Selection.Find.Found Then
      'And this page hasn't been printed
      If Selection.Information(wdActiveEndPageNumber) <> LastPrintedPage Then
        'Print current page
        Application.PrintOut Range:=wdPrintCurrentPage
        'Remember the last printed page number
        LastPrintedPage = Selection.Information(wdActiveEndPageNumber)
      End If
    End If
  Loop Until Selection.Find.Found = False

End Sub


Ture Magnusson
Karlstad, Sweden
0
 
LVL 22

Expert Comment

by:ture
ID: 2618965
Here is a slightly more compact version:

Sub PrintPagesWithCodeword()
  'Prints all pages with a given string
 
  'Declare variables
  Dim Message As String
  Dim Title As String
  Dim Default As String
  Dim SpecialCode As String
  Dim LastPrintedPage As Long
 
  'Read SpecialCode from user
  Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
  Title = "PrintPagesWithCodeword"
  Default = "XYZ"   ' Set default, is set as case sensitive below.
  SpecialCode = InputBox(Message, Title, Default)
 
  'Move selection to beginning of document
  Selection.HomeKey Unit:=wdStory
 
  'Set parameters for Find
  With Selection.Find
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = True
    .MatchAllWordForms = False
    .MatchFuzzy = False
    .MatchSoundsLike = False
    .MatchWholeWord = True
    .MatchWildcards = False
  End With
 
  'Keep finding while the text is found
  Do While Selection.Find.Execute(FindText:=SpecialCode)
    'If this page hasn't been printed
    If Selection.Information(wdActiveEndPageNumber) <> LastPrintedPage Then
      'Print current page
      Application.PrintOut Range:=wdPrintCurrentPage
      'Remember the last printed page number
      LastPrintedPage = Selection.Information(wdActiveEndPageNumber)
    End If
  Loop

End Sub

/Ture
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 2619276
Cri,

I've tested my macro with a printer now, and it is effectively the Selection.Find.Execute command without further specification not working correctly.

So, My code works, and prints the correct pages. Of course Ture's macro will include a single time print for pages including more than  match, which is another imporvement.

This one will do it to:

Sub PrintPagesWithCodeword()

                   'Prints all pages with a given string

                       Dim Message As String, Title As String, Default As String, SpecialCode As String
                       Dim b As Integer                            
                       Message = "Only pages containing following text (case sensitive) will be printed: " ' Set
                   prompt
                       Title = "PrintPagesWithCodeword"
                       Default = "XYZ"   ' Set default, is set as case sensitive below.
                       SpecialCode = InputBox(Message, Title, Default)
                           
                       Selection.HomeKey Unit:=wdStory  'start at the beginning
                       With ActiveDocument.Content.Find
                          Do While .Execute(FindText:=SpecialCode, Forward:=True, MatchCase:=True) = True
                             Selection.Find.Execute FindText:=SpecialCode, Forward:=True, MatchCase:=True
                         If Selection.Information(wdActiveEndPageNumber) <> b                            Then
                           b = Selection.Information(wdActiveEndPageNumber)
                           Application.PrintOut Range:=wdPrintCurrentPage
                          End If
                          Loop
                       End With

                   End Sub

Good Luck

Calacuccia
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 2619281
OOPS, sorry about the formatting (scrappy Netscape browser)
0
 
LVL 4

Expert Comment

by:wesleystewart
ID: 2619538
ture's idea for preventing multiple prints of the same page is a good catch.  It never occurred to me that the keyword might appear on the same page more than once.

Wes
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 13

Author Comment

by:cri
ID: 2621334
Oh my, will be though to award this one: wesleystewart's _correction_ works on my PC and therefore is prime candidate, ture's enhanced one surely will, the other ones I did not yet test.
 
I will leave it open, must call ACS.  
0
 
LVL 4

Expert Comment

by:wesleystewart
ID: 2621346
By all means be sure to use ture's code to trap for pages where the string shows up several times.

Wes
0
 
LVL 13

Author Comment

by:cri
ID: 2621365
wesleystewart, very noble of you, but I _think_ the code is no common word but unique. Additionally, _my_ question was what was wrong with my code, and you got it first.
But I will leave the decision to ACS.
0
 
LVL 5

Expert Comment

by:vboukhar
ID: 2622973
Just a note:
I wonder, why my idea for preventing multiple prints of the same page is conserned as ture's one - my code was first :-) All rights reserved :-)
0
 
LVL 4

Expert Comment

by:wesleystewart
ID: 2623576
vboukhar:

I apologize, I hadn't read your post thoroughly.  Ture's note:

"4. You should make sure that the same page is not printed more than once, even if it contains more than one instance of the SpecialCode text"

caught my eye first.  For the record:  you contributed that idea first.

Wes
0
 
LVL 22

Expert Comment

by:ture
ID: 2623631
vboukhar,

No - Cri was first! Our task here is to improve his original code.

Yes - we had the same idea. We both wanted to avoid printing the same page twice. But we used quite different solutions to achieve that. I really don't think that our VBA procedures are very similar.

/Ture
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 2626026
VBoukhar, add my apologies to your list of greatest reconciliations, as I, for some obscure reason, did not read your comment attentively enough. You were, and that's a fact, the first one to have mentioned the possibility of having two matches on the same page.

Ture, Cri was first, as is any person who asks a question here, VBoukhar definitely was the first one to explicitely state the possibility of having two or more matches on the same page..............
0
 
LVL 13

Author Comment

by:cri
ID: 2633952
So, its time to close this one.

I will award the following:

a) Question goes to wesleystewart s/he found my errors as first

b) 50 points to calaccucia as ACS will use his solution
 
Ture thanks for the explanation, vboukhar thanks for the enhancement
TigerMan, thank you for tackling my problem
0
 
LVL 5

Expert Comment

by:TigerMan
ID: 2634062
cri,

The TigerMan gracefully bows out of the need for any reward.  My efforts were trivial and uninformed, and relied on the thinking of others.

My reward however is a new interest in VB and Word.

A man cannot step into the same river twice [Heraclitus, circa 200 AD].


Dave
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 2634073
Thanks, Cri.

I swear I want be swearing no more <g>

Calacuccia
0
 
LVL 4

Expert Comment

by:wesleystewart
ID: 2635866
Happy to help out.

As of this morning, I was a "he"

Wes
0
 
LVL 22

Expert Comment

by:ture
ID: 2635877
Cri,
It was a joy to participate!
/Ture
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

In this article we discuss how to recover the missing Outlook 2011 for Mac data like Emails and Contacts manually.
This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
This video shows where to find the word count, how to display it, and what it breaks down to in Microsoft Word.
The viewer will learn how to simulate a series of coin tosses with the rand() function and learn how to make these “tosses” depend on a predetermined probability. Flipping Coins in Excel: Enter =RAND() into cell A2: Recalculate the random variable…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now