Microsoft Office Forums

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 12-11-2012, 12:12 PM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default Replace text with Quick Part using VBA


I'm pretty new to VBA so please bear with me!

I'm attempting to streamline a Word document that I use over and over and over. I've written a macro to fix the grammatical errors that are always present but I need to replace a couple separate instances of text with a person's name throughout the document. For example, I need to replace both "your name" and "student" with "Ann Robertson". The actual name like "Ann Robertson" is already in the document inside a quick part named "Person". I'm using quick parts because occasionally the name will change, e.g. from Ann Robertson" to "Ann M. Robertson". Is it possible to do a sort of find and replace w/ VBA? I've found the "insert quickpart" code but I'm too new to know what to do with it.

Thank you all in advance for your time. The knowledge I've gained on this forum is great!
Reply With Quote
  #2  
Old 12-11-2012, 01:01 PM
gmaxey gmaxey is offline Replace text with Quick Part using VBA Windows 7 32bit Replace text with Quick Part using VBA Office 2010 (Version 14.0)
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,421
gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough
Default

There are a couple of ways to do this. My VBA Find and Replace Add-In has this feature: http://gregmaxey.com/word_tip_pages/...d_replace.html

The first macro below uses the process where the building block is inserted in a temporary document then cut to the clipboard. The clipboard content is then used as the "Replace with" and you can do a global replacement. The second macro simply inserts the builiding block at the found ranges. It assumes that your building block is in the attached template. If that isn't the case, you will have to change the code.


PHP Code:
Sub ReplaceWithAUTOTEXT()
Dim strFind As String
Dim strReplace 
As String
Dim strWildcards 
As String
Dim bWild 
As Boolean
Dim strQuery 
As String
Dim sType 
As String
Start
:
strFind InputBox("Enter the text string you want to find""Find")
If 
strFind "" Then
    strQuery 
MsgBox("You have not entered any text to find" vbCr _
    
"Or you have selected 'Cancel" vbCr _
    
"Select OK to re-try or Cancel to quit"vbOKCancel"Find")
    If 
strQuery vbOK Then
        
GoTo Start
    
Else
        Exit 
Sub
    End 
If
End If
strWildcards MsgBox("Use Wildcards"vbYesNo"Find")
If 
strWildcards 6 Then bWild True Else bWild False
GetInput
:
On Error GoTo Oops 'Handle incorrect AutoText request
'
Create a scratch pad
Documents
.Add
If Application.Version 12 Then
'Word 2007 - Use the Building Blocks Organizer
    Dialogs(GetDialog).Show
    sType = "Building Blocks" '
msgbox title
Else
'Not Word 2007 - Use the Autotext dialog.
    Dialogs(wdDialogEditAutoText).Show
    sType = "Autotext" '
msgbox title
End 
If
'Cut the inserted entry to the clipboard
Selection.HomeKey Unit:=wdStory, Extend:=wdExtend
Selection.Cut
'
crumple up scratch pad :-)
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
'Replace found text with the clipboard contents.
With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = strFind
    .Replacement.Text = "^c"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = bWild
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
End With
End
Oops: '
Error handler
ActiveDocument
.Close SaveChanges:=wdDoNotSaveChanges
strQuery 
MsgBox("Select 'OK' to reselect the " sType _
" entry then click 'Insert'" vbCr vbCr _
"Click 'Cancel' to exit"vbOKCancelsType)
If 
strQuery vbOK Then
    Resume GetInput
End 
If
End Sub
Sub ReplaceWithAUTOTEXTII
()
Dim oRng As Word.Range
Dim strFind
() As String
Dim i 
As Long
strFind
() = Split("student|your name""|")
For 
0 To UBound(strFind)
  
Set oRng ActiveDocument.Range
  With oRng
.Find
    
.ClearFormatting
    
.Replacement.ClearFormatting
    
.Text strFind(i)
    .
Forward True
    
.Wrap wdFindContinue
    
.Format False
    
.MatchCase False
    
.MatchWholeWord False
    
.MatchWildcards False
    
.MatchSoundsLike False
    
.MatchAllWordForms False
    
While .Execute
      ActiveDocument
.AttachedTemplate.BuildingBlockEntries("Confidential").Insert Where:=oRngRichText:=True
    Wend
  End With
Next
End Sub 
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote
  #3  
Old 12-11-2012, 01:48 PM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default

Thank you Greg, that worked beautifully. I misspoke in my initial question by referencing "quick parts". After reading through some of your site I think what I want to insert is a content control (document property??) throughout the document at the specific places where the text "student" or "your name" appears as you did here:

strFind() = Split("student|your name", "|")

(I would like to be able to change the text using the content control (or Document property) at a later date. When I created this document I "stole" one of the document property fields and renamed it. It's nice to be able to type the name in one spot and have it populate thoughout the document.)

Thank you again for your help!
Reply With Quote
  #4  
Old 12-11-2012, 01:51 PM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default

I don't know if it would be easier/better to write the code so that it places the content controls wherever the macro finds "student" or "your name" and then have a pop-up that requests the actual name like "amy robertson"? I'm already in over my head so any help/suggestions are appreciated. Once the content controls are placed it's just as easy to type in the name and populate the remaining fields that way.
Reply With Quote
  #5  
Old 12-11-2012, 02:16 PM
gmaxey gmaxey is offline Replace text with Quick Part using VBA Windows 7 32bit Replace text with Quick Part using VBA Office 2010 (Version 14.0)
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,421
gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough
Default

dmarie,

I'm over my head all the time, but isn't it more fun in the deep end?

Document Properties (e.g., title, subject, comments, etc.) are stored in one of three built-in customXMLParts in a document. So, if you want you can find text and replace it with a content control and then bind that CC to the customXMLpart data node:

PHP Code:
Option Explicit
Sub ReplaceWithConentControlBoundToABuiltInDocProperty
()
Dim oRng As Word.Range
Dim strFind
() As String
Dim strInput 
As String
Dim i 
As Long
Dim oCC 
As ContentControl
strFind
() = Split("student|your name""|")
strInput InputBox("Enter the replacement name:""Input")
For 
0 To UBound(strFind)
  
Set oRng ActiveDocument.Range
  With oRng
.Find
    
.ClearFormatting
    
.Replacement.ClearFormatting
    
.Text strFind(i)
    .
Forward True
    
.Wrap wdFindContinue
    
.Format False
    
.MatchCase False
    
.MatchWholeWord False
    
.MatchWildcards False
    
.MatchSoundsLike False
    
.MatchAllWordForms False
    
While .Execute
      Set oCC 
ActiveDocument.ContentControls.Add(wdContentControlTextoRng)
      
With oCC
        
'High jack the "Comments" document property.
        .XMLMapping.SetMapping "ns1:coreProperties[1]/ns0:description[1]", , ActiveDocument.CustomXMLParts(1)
        .Range.Text = strInput
        .Title = "Name"
      End With
    Wend
  End With
Next
End Sub

Sub ScratchMacro()
'
This tells you some of the other node names and XPath
Dim oCXNOde 
As CustomXMLNode
Dim oCXNodes 
As CustomXMLNodes
Set oCXNodes 
ActiveDocument.CustomXMLParts(1).SelectNodes("//*")
For 
Each oCXNOde In oCXNodes
  Debug
.Print oCXNOde.BaseName " " oCXNOde.XPath
Next
End Sub 
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote
  #6  
Old 12-12-2012, 10:27 AM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default

I do like the deep end...hahaha! Thank you Greg for your help with this!!

I have a few questions (big shocker, I know )

1. The macro works for but it's only changing the first instance of "This student". When I first ran it it worked for every instance...
I get a Run-time error 4198? When I debug the following line is highlighted:
Set oCC = ActiveDocument.ContentControls.Add(wdContentContro lText, oRng)

I have other document properties in the word doc, I'm not sure if that's problematic, I wouldn't think so but see previous post about "in over my head"?

2. Can I add more parameters? Like this:
strFind() = Split("This student|student|STUDENT|this Student|This Student", "|") and then change the MatchCase to True?

3. I'm wondering if there is a Not statement I can tie in? In SQL you can basically say look for "student" but not "my student" and then when you find the correct one replace it with "Ann Smith". Is selective replacing possible w/ VBA? The word "student" appears in areas of general text and should not be changed to the proper name (that is now tied to the content control). Also, the word "students" appears randomly and I don't want that to change. I tried changing it from False to True for .MatchWholeWord but then it didn't recognize both terms...It's not specific areas or I would be asking for help with ranges haha.

Thank you in advance (again) for your help. I'm trying to figure these things out before I post. So far I just have a headache .

Last edited by dmarie123; 12-12-2012 at 12:03 PM.
Reply With Quote
  #7  
Old 12-12-2012, 02:05 PM
gmaxey gmaxey is offline Replace text with Quick Part using VBA Windows 7 32bit Replace text with Quick Part using VBA Office 2010 (Version 14.0)
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,421
gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough
Default

It continues to run here. The error sounds like the range spans an existing CC. Start with a fresh version of the document and see if it won't work:

PHP Code:
Sub ReplaceWithConentControlBoundToABuiltInDocProperty()
Dim oRng As Word.Range
Dim strFind
() As String
Dim strInput 
As String
Dim i 
As Long
Dim oCC 
As ContentControl
strFind
() = Split("This student|STUDENT|your name""|")
strInput InputBox("Enter the replacement name:""Input")
For 
0 To UBound(strFind)
  
Set oRng ActiveDocument.Range
  With oRng
.Find
    
.ClearFormatting
    
.Replacement.ClearFormatting
    
.Text strFind(i)
    .
Forward True
    
.Wrap wdFindContinue
    
.Format False
    
.MatchCase False
    
.MatchWholeWord True
    
.MatchWildcards False
    
.MatchSoundsLike False
    
.MatchAllWordForms False
    
While .Execute
      Set oCC 
ActiveDocument.ContentControls.Add(wdContentControlTextoRng)
      
With oCC
        
'High jack the "Comments" document property.
        .XMLMapping.SetMapping "ns1:coreProperties[1]/ns0:description[1]", , ActiveDocument.CustomXMLParts(1)
        .Range.Text = strInput
        .Title = "Name"
      End With
    Wend
  End With
Next
End Sub 
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote
  #8  
Old 12-12-2012, 02:41 PM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default

Thanks Greg, that did the trick. Is there a way to exclude text in the search parameters?
Reply With Quote
  #9  
Old 12-12-2012, 07:05 PM
gmaxey gmaxey is offline Replace text with Quick Part using VBA Windows 7 32bit Replace text with Quick Part using VBA Office 2010 (Version 14.0)
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,421
gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough
Default

Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim strFind() As String
Dim i As Long
Dim oRng As Word.Range
strFind = Split("this student|a student|my student|student", "|")
For i = 0 To UBound(strFind)
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Text = strFind(i)
.MatchWholeWord = True
.MatchCase = False
While .Execute
oRng.Select
If MsgBox("Process this instance", vbYesNo, "Process?") = vbYes Then
oRng.Text = "whatever"
End If
Wend
End With
Next i
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote
  #10  
Old 12-13-2012, 08:10 AM
dmarie123 dmarie123 is offline Replace text with Quick Part using VBA Windows 7 64bit Replace text with Quick Part using VBA Office 2007
Novice
Replace text with Quick Part using VBA
 
Join Date: Dec 2012
Location: New Yuk
Posts: 23
dmarie123 is on a distinguished road
Default

Thank you!!
Reply With Quote
  #11  
Old 09-18-2014, 01:03 AM
TimK TimK is offline Replace text with Quick Part using VBA Windows 7 32bit Replace text with Quick Part using VBA Office 2010 32bit
Novice
 
Join Date: Sep 2014
Posts: 1
TimK is on a distinguished road
Default

I know this thread is really old, but this code looks close to what I need, but I'm wanting to add a MS SharePoint server document property and this code seems to be adding something different.

Would appreciate some assistance.

Thanks in advance :-)

Tim
Reply With Quote
Reply

Tags
content control, vba in microsoft word, word 2007

Thread Tools
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Replace text with Quick Part using VBA Macro to find text and replace with form field containing that text iiiiifffff Word VBA 16 06-04-2016 01:47 AM
How to Rename a Quick Part sleake Word 14 10-14-2013 09:21 AM
quick replace, sort, change columns userman Excel 1 05-01-2012 06:24 AM
Quick change for all text boxes in a presentation tmlander PowerPoint 1 03-09-2012 01:20 AM
Date display in Mod quick part header Jrul John Word 1 08-02-2010 12:17 PM

Other Forums: Access Forums

All times are GMT -7. The time now is 10:00 AM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft