loop macro in word 2002 Results


Sponsored Links:



I want to create a macro for a document that only has addresses that does a "Keep lines together" for all addresses in document so I want a macro that loops as many times as necessary until it's done. I have a series of commands (1. turn select mode on, 2. find Paragraph Marker, Paragraph Marker, 3. turn on Para keep lines together, 4. search again and continue the loop as many times as necessary to go through entire document). I can't seem to figure out the looping in Word (I have it for Word Perfect but not Word). Any help would be greatly appreciated!!




I have an elaborate macro that loops through a (former WordPerfect) document multiple times to find various double-bracketed strings and then performs various formatting actions when it finds them. The macro works perfectly in its original version, but I've started to rewrite some of the code to work as much as I can with the Range.Find object rather than the Selection.Find object. For the most part, this is working, but some of the rewritten searches cause Word to freeze, forcing me to use Task Manager to shut it down.

The freezes always seem to happen in the immediate wake of a Range.Find that came up empty. Where it's a simple Find loop that is causing the freeze and the document has instances of the target, the code runs fine until it performs the final .Execute that returns False. Where it's a ReplaceAll version of .Execute, the code runs fine unless there are no instances of the target in the document.

The freezes are erratic only in the sense that much of my rewritten Range.Find code is working fine (including when the search comes up empty). But the freezes are consistent in the sense that a particular Range.Find that freezes in a particular document will always freeze at that same point in that same document (including if I'm stepping through the code).

Has anyone else experienced this kind of bugginess with Range.Find in Word 2002?

(P.S. I've tried throwing in DoEvents and pauses using Timer, but these haven't had any effect.)

(P.P.S. I should add that these are not "converted" WordPerfect documents. I'm copying the WordPerfect documents' contents (stripped of all codes) to the clipboard and pasting them into Word as unformatted text -- so I don't think the WordPerfect origin has anything to do with the Range.Find problem.)




Due to a client using a third-party package, when we regenerate their TOC in Word 2002 it brings in the entire paragragh due to the formatting of their file. I wrote a macro that once the TOC is generated it will delete the extra text. But I am having difficulties doing it using a loop, so right now I have the secretary pressing a speed key which goes line by line through the resulting table. I have tried getting it to work but have not had success. Below is what works line by line.

Selection.Paragraphs.First.Range.Select

Selection.Font.Reset
Selection.Find.ClearFormatting

With Selection.Find
.Text = "."
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Find.Execute
Selection.Extend
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^t"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.Delete Unit:=wdCharacter, Count:=1
Selection.MoveDown Unit:=wdLine, Count:=1
End Sub

Hoping someone can give me some assistance,
Mary Lou Palace




In WordPerfect I always had a simple input dialog (called by Alt-M) that took the name of a macro and ran it -- or retrieved the macro for editing if I clicked on a separate button. I'm replicating it in Word and can use the following code to pull up the macro in the VBEditor:

For Each vbcX In projRUW.VBComponents
If vbcX.Type = vbext_ct_StdModule Then
Set mdl = vbcX.CodeModule
If mdl.Find("Sub " & strName, lngSLine, lngSCol, lngELine, lngECol) Then
mdl.CodePane.Show
lngX = mdl.ProcBodyLine(strName, vbext_pk_Proc)
mdl.CodePane.SetSelection lngX + 1, 1, lngX + 1, 1
Exit Sub
Else
If mdl.Find("Function " & strName, lngSLine, lngSCol, lngELine, lngECol) Then
mdl.CodePane.Show
lngX = mdl.ProcBodyLine(strName, vbext_pk_Proc)
mdl.CodePane.SetSelection lngX + 1, 1, lngX + 1, 1
Exit Sub
End If
End If
End If
Next vbcX

Isn't there a more direct way?

I tried assigning mdl.ProcStartLine(strName, vbext_pk_Proc) to lngX near the top of the loop (where the first .Find line is), figuring lngX would be 0 if the module lacked a procedure with that name, but instead I get error 35 ("sub or function not defined").

Is there a way that complete avoids looping through the modules and instead makes reference to some kind of index that Word must surely maintain for all currently available macros?




WordPerfect's macro language includes a Pause command that pauses the macro (often within a loop) and resumes execution when the user hits a particular key (or key-combination). So, to take a simple example, you can create a looping macro that allows the user to move through a long list and create a 2nd list with only selected items from the original list by hitting Ctrl-Enter while the cursor is located on each item to be copied to the 2nd list. There's no dialog box involved.

I don't think I can exactly replicate this in Word, but I'd like to find the best alternative. One possibility (that I haven't yet tried) might be a VBA macro that (1) assigns a 2nd macro (that actually performs the relevant copy or whatever) to Ctrl-Enter, (2) puts a small modeless UserForm in one corner of the screen with nothing but a Cancel button, and (3) returns the Ctrl-Enter key to its original assignment after the user cancels the UserForm.

I'd be interested in hearing how other Loungers have handled this kind of situation.




I have a word template in my startup folder. This has a DocumentChange event which fires whenever the focus switches to a different word document. It is used to modify a number of application specific toolbars.

The code called from the event changes CustomizationContext to the attached template and to the Global template containing the event code, and enables / disables various toolbar controls. It manipulates the .Saved property of the templates so that it doesn't "dirty" them with it's changes.

This code works perfectly on Word 2000 and Word 2002, but on Word 2003 it generates an infinite loop whenever the user vists the header of a document. Single stepping the code I can see that the code runs to completion and then the event immediately fires again. This is not a recursion - it does complete each time and exits at the final End Sub. It is almost as though there is an event queue waiting for the macro to exit. It only happens if the user double clicks in the header of a document (or possibly a footer, I haven't checked this).

I tried setting a boolean variable at the beginning of the event routine and immediately exiting if I find it true, but since this is not recursion it didn't help. I also tried inserting a DoEvents before exiting to see if that helped, but it still waits till the Exit Sub before starting again! I even tried disabling events by putting
Set AppEvents.App = Nothing
Set AppEvents.App = Word.Application

at the beginning and end of the event code, but this didn't help either.

Any suggestions?

StuartR




I'm getting consistent bugginess trying to search for the Normal style using a Range if (1) there's a table in the document, and (2) either there are no Normal paragraphs in the document or the only Normal paragraphs precede the table.

To take a simple example: If I create a new document consisting of nothing but a handful of Body Text paragraphs and a table (with the table positioned several paragraphs down from the start of the document), and then I run the following code:
Dim rngX As Word.Range
Dim lngCount As Long

Set rngX = ActiveDocument.Range(0, 0)
With rngX.Find
.Text = ""
.Style = "Normal"
.Format = True
End With
With rngX
Do While .Find.Execute = True
lngCount = lngCount + 1
Debug.Print "Found at " & .Start & ", " & .End
.Collapse wdCollapseEnd
If lngCount = 3 Then
Exit Do
End If
Loop
End With

Set rngX = Nothing

the result in the Immediate Window is:
Found at 0, 0
Found at 0, 0
Found at 0, 0

Somehow .Find.Execute is returning True and yet rngX isn't moving forward to any found target. The code would loop endlessly if not for the "If lngCount = 3" exit line. And what's worse: If I set up the code so that it's replacing Normal with another style, Word tends to crash. (During one series of tests, it was pretty consistently crashing the 2nd time I ran the macro -- as if the first execution somehow put the document (or Word) in an unstable state, after which the 2nd execution delivered the knockout punch.)

Some further experimentation involving the Selection object leads me to the conclusion that it's the end-of-row-markers in the table that are causing the problem. They're "Normal" style but they confuse Range.Find objects.

Further note: If I change one of the paragraphs after the table to Normal style and then run the code, it works perfectly. (Likewise if I start the .Find with the Range already located after the table.)

I realize one possible "solution" is to just make sure none of my documents ever have any "Normal" paragraphs (not counting end-of-row-markers), so I never have any reason to run a procedure that searches for the Normal style. Perhaps another "solution" would be to use the Selection object, although I don't really know that it's not also subject to some bugginess in this area.

Is there a more direct solution -- i.e., a way to prevent the end-of-row markers from screwing up the Range.Find object?




(Edited by st3333ve on 09-Jul-04 23:39. )If I try to insert any of several of the built-in AutoText entries that includes a date (e.g., Author, Page #, Date in the Header/Footer category, or Last printed), Word stops responding. The first time I experienced this, the AutoRecovered copy of the document it happened to showed that Word had gone into a loop and entered the date over and over and over and over. Since then there haven't been any AutoRecovered copies to examine, but it happens consistently.

If I go to the AutoText tab of the Tools-->AutoCorrect Options dialog and select any of the problematic entries in this dialog, Word also stops responding.

I renamed Normal.dot and let Word generate a fresh Normal template and have temporarily moved my macros template out of the Startup folder, but this "clean" version of Word is misbehaving in the same way.

Has anyone else encountered this?

If anyone who hasn't made use of these AutoText entries is inclined to try to replicate my problem, I urge you to first exit out of (don't just save) any open documents first.

FOLLOW-UP NOTE: By using the Office Application Recovery tool, I was able to recover another frozen document. This time I had tried to insert the Created on entry, and once again, the "freeze" was caused by Word inserting the date over and over and over and over. (This time it happened with the "clean" version of Word -- i.e., a newly-created Normal template and no global templates loaded.)




I have a user who created a recorded Excel macro that changes their active printer in Excel to one located on another floor. The macro then prints and sets them back to their current printer. It works fine until we add new printers or re-build their PCs and install printers in a different order (because of the NeXX: number). It is also used by several people, complicating the printer installation process. I am trying to fix this problem for them but I am more experienced in Word VBA. I have used this type of code in Word and it works fine:

Sub Print_sheet_elsewhere()
Dim strDefPrinter As String
Dim strSwiftPrinter As String
strDefPrinter = Application.ActivePrinter
strSwiftPrinter = "RBNZ_DCKSG-DC1"
Application.ActivePrinter = strSwiftPrinter
ActiveWindow.PrintOut Copies:=1
Application.ActivePrinter = strDefPrinter
End Sub

When I try the same code in Excel, it refuses to set the Activeprinter until you specify it this way:

Sub Print_sheet_elsewhere()
Dim strDefPrinter As String
Dim strSwiftPrinter As String
strDefPrinter = Application.ActivePrinter
strSwiftPrinter = " RBNZ_DCKSG-DC1 on NE03:"
Application.ActivePrinter = strSwiftPrinter
ActiveSheet.PrintOut Copies:=1
Application.ActivePrinter = strDefPrinter
End Sub

I searched through posts here and found one (number 55355) that suggested doing something like..........

CurPrntr= Application.ActivePrinter
If Right(CurPrntr,5)="Ne00:" then Application.ActivePrinter = _
PrinterOnNE01
Else Application.ActivePrinter = PrinterOnNE00
Print Routine here
Application.ActivePrinter = CurPrntr

But some of our people have up to 10 network printers installed, meaning I would have to loop through them... Can anyone suggest a way I can do this? Or alternatively can you specify the printer without finding the NE number as you can in word.

Belinda




Trying to write a macro to adjust page setup options in a document containing sections. I can get it to work in section 1, have tried different code to loop through all sections, but have not succeeded. Below is what works in one section. Help is greatly appreciated.

With ActiveDocument
.UpdateStylesOnOpen = True
.AttachedTemplate = "h:importSpecifications.dot"
End With
With ActiveDocument
.UpdateStylesOnOpen = False
End With

With Selection.PageSetup

.LineNumbering.Active = False
.TopMargin = InchesToPoints(1.1)
.BottomMargin = InchesToPoints(1)
.LeftMargin = InchesToPoints(1)
.RightMargin = InchesToPoints(1)
.HeaderDistance = InchesToPoints(0.5)
.FooterDistance = InchesToPoints(0.5)
.PageWidth = InchesToPoints(8.27)
.PageHeight = InchesToPoints(11.69)
.FirstPageTray = wdPrinterDefaultBin
.OtherPagesTray = wdPrinterDefaultBin

End With




YAY!!! Woodys back online i was sooo suffering withdrawl symptoms

I need to write some code that prints pages containing Words track changes
later I will build the heading style Deltaview (which is "track changes")

This is my pseudo...

View Final Shop Markup
Goto start of doc
in a loop
Goto next track change
obtain page number - store in array
Goto next page
end loop

print array (which contains the page number)

I was recording a macro or "skeleton" code for me to work from, the code for track changes is in WordBasic?

WordBasic.NextChangeOrComment

Is there syntax more current?

Is there any existing similar code, that would help me get started would be greatly appreciated

many thanks

diana




Last night I compiled and then tried to save a global template (containing macros) that I had open in the VBE window. Hitting the Save button was followed by endless hard drive activity. I finally shut Word down with the Task Manager, after which I found that the Startup directory (where the template resides) contained a ~xxx.tmp file that was around 550 MB. I had this same experience a while back, with a different global macro template, and that time (after I waited longer to shut Word down) the resulting ~xxx.tmp file was around 1 GB. (I suspect that, in each case, Word was in some kind of loop and would have filled the whole hard drive with the tmp file if I hadn't shut it down.)

The template I was trying to save was around 1.2 MB and wasn't dramatically bloated. (After the hang, I copied its modules into a new template, compiled and saved, and that reduced it to around 900 KB.)

I'm pretty good about saving my work, so I didn't lose much this time, but I'm wondering:

1. Have others experienced this? Once in a blue moon? On a semi-regular basis?

2. Any insight into causes and/or tips on how to avoid?




I recently posted about the issue that, when you change a paragraph's style, Word deletes any direct character formatting that involves more than half the paragraph. In an earlier thread that I found, one of the Lounge wise men had noted that this doesn't happen if you change the paragraph's style using Find/Replace, so I've been playing around with an "ApplyTheStyle" macro that uses that technique.

I've been having no problems for the most part, except within tables. To illustrate my (replicable, I expect) problem, here's some sample code that loops through a document's paragraphs and changes each paragraph's style to Normal using Find/Replace:

Dim oPar As Word.Paragraph
Dim oRng As Word.Range

For Each oPar In ActiveDocument.Paragraphs
Set oRng = oPar.Range
oRng.Collapse wdCollapseStart
If oRng.Style "Table Grid" Then
With oRng.Find
.Format = True
.Style = oPar.Style
.Replacement.Style = "Normal"
.Execute Replace:=wdReplaceOne
End With
End If
Next oPar

Set oRng = Nothing

If I create a new document, add a few Body Text paragraphs, then create a 4-column, several-row table using the toolbar button while the cursor's in a Body Text paragraph, all the table's cells are styled Body Text.

Now if I run the above code, it works until it reaches the 2nd row of the table, at which point Word freezes and needs to be shut down with Task Manager.

If I comment out the If oRng.Style "Table Grid" line (and its corresponding End If), the freeze happens a little sooner (in the 2nd cell of the first row).

Besides being puzzled by the freezes, I'm also puzzled about why, when I change the style of the first cell in a row using Find/Replace, it changes the style of every cell in the row. This seems to be related to the freeze that happens in the 2nd cell of the first row if I comment out the "Table Grid" check. In that case, after the Find/Replace has changed the first cell's style to "Normal" (and hence indirectly changed the whole row's style to Normal), the freeze happens in the 2nd cell under circumstances where oRng.Style is "Table Grid" but oPar.Style is "Normal" (I learned this by adding Debug.Print lines in the middle of the loop) -- even though oRng has just been set to oPar.Range (so I would think oPar.Style and oRng.Style would be the same).

1. Can anyone shed light on why Word is freezing?

2. Can anyone explain why the Find/Replace of the style in the first cell changes the style for the whole row?




The "Accept" and "Reject" buttons in the Word 2002 Reviewers toolbar do not automatically jump to the next revision, as the 2000 version buttons did. Believe it or not, this change has prompted a halt in the deployment of Windows and Office XP to our staff.
I have opened two cases with MSDN tech. support trying to find an answer, and the closest we came to one was by displaying the 2000 Reviewers toolbar under Word 2002. But, alas, it does not work with comments. I have also looked at code from the MSDN folk (and some in this forum) that loops through revisions and/or comments in various ways. But none of this is quite the same, unfortunately, as having a pair of buttons on the toolbar that would accept or reject a change or comment and move to the next one. I tried to record these actions into macros, but the resulting code does not work reliably.

If your sympathy for a very frustrated sysadmin would allow it, would you be kind enough to tell me if this is possible and, if so, help us to do it?




Hi !
This is my code.
It's making a list of some highligted sentences in a document.
But it has no format. Like colors...
What change must do ? With colors and when the color changed, type a paragraph…
Please see the NOTE-1 and NOTE-2 in the attachment document.

Sub Highligtedselection()
Dim hah As String
Selection.HomeKey Unit:=wdStory
With Selection.Find
.Text = ""
.Format = True
.Highlight = True
ReDim b(1000)
Do While .Execute
i = i + 1
hah = Selection.Text
b(i) = hah
Selection.MoveRight Unit:=wdCharacter, Count:=1
Loop
.Execute
End With
Selection.EndKey Unit:=wdStory
Selection.TypeText Text:="RAPOR:"
For e = 1 To i
Selection.TypeText Text:=b(e)
Next
End Sub




Hi,
I'm trying to get this macro to delete the whole row if the word "delete" is located in column I. Obviously I have a coding problem... anyone have any ideas why it isn't working. I don't actually get any error messages... it acts like it's running thru all the rows trying to find the word "delete", but it never actually deletes any rows.
Thanks!
Lana

Sub DeleteRows()

Dim lngRow As Long

lngRow = 2

Do While Sheets("data-complete").Range("A" & lngRow) ""

If Sheets("data-complete").Range("I" & lngRow) = "Delete" Then
Sheets("data-complete").Range("A" & lngRow).Delete Shift:=xlShiftUp

End If

lngRow = lngRow + 1
Loop

End Sub




I've been given an old textbook glossary that we want to update with terms from our new dictionary (which contains combined, updated terms from all of our textbooks). I tried merging the two documents, but the results were quite messy. I recorded a macro to do the job, but it doesn't work. There are three problems (that I can see) with the macro.

First, when I recorded the macro, I pasted the contents of the clipboard into the Find What box. But when I opened the macro, it had the term of the first word I searched for. I changed that to Selection.Paste, which seemed like it would have worked. It didn't. I thought of using ^c and selecting Use Wildcards, but the old glossary terms are all caps, and the dictionary are only capped where appropriate. (I just tried it anyway, and it gave a runtime error.)

Second, I'm not sure what to do about terms that aren't in the master dictionary. What I would like to happen is for the term that's not in newglossary.doc to be pasted into it. Instead, it goes to the next paragraph and deletes the next character.

Third, I don't know how to make it loop so that it runs the macro on the entire file. This function would save me minutes, as opposed to the rest of the puzzle, which will save me hours. Still, it's something that I could probably use every time we update a textbook in the future.

I'd attach the documents, but the master dictionary is quite large. If it would help, I could create a new file with just the first several pages. The macro I recorded is below.

' NewSMA3Glossary Macro
' Macro recorded 9/23/2004 by Michael Coleman
'
Selection.MoveDown Unit:=wdParagraph, Count:=1
Selection.Extend
Selection.Extend Character:="."
Selection.Copy
Selection.EscapeKey
Selection.HomeKey Unit:=wdLine
Windows("newglossary").Activate
Selection.Extend
Selection.Find.ClearFormatting
With Selection.Find
.Text = "Selection.Paste"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
Application.Run MacroName:="TemplateProject.DeleteCharRight.MAIN"
Selection.MoveDown Unit:=wdParagraph, Count:=1
Windows("oldglossary").Activate
End Sub

I don't know if I'm asking one macro to do too much. I'm pretty certain it can work, though. If someone has the inclination to take up this puzzle, I would be, as always, very grateful.

Thank you,




My office 2002 has, for some time, been very wacky. To name a few idiosyncacies:
1. Outlook hangs up word when using HTML quite often
2. Word refuses to save new macros
3. regularly can't save Normal.dot and get into an "in use" loop.
4. Cannot do Control A in an excel file
5. Adobe Acrobat hangs up when converting Word.
6. and so on
I've been advised to unistall Office XP and resinstall from discs. A pain, but if it works, worth it. so, my qustion is, can i find a nice list of locations for Office files I want to re-use, such as my dictionary, autotext, templates and so on? (I'm leery of using the old Normal.dot.)

Many thanks,
Michael