简体   繁体   中英

How do I modify Plain Text Content Control in Word via MS Excel VBA

I am using MS Excel VBA to copy Cells from Excel to Word. I established Plain Text Control Fields in my Word Document and add Values from my Excel Document.

Before I add them via VBA code, I open the Word Document and activate it (like in the code below).

Now there are quotation marks in my plain text control fields after inserting the copied text. I want to replace quotation marks in Content Control Object (3) with "space".

Why do I not just delete it manually? Because I established drop down fields in my Excel Document and change them quickly. After changing them I generate new Values and insert them again in my word document.

I hope someone can tell me, how to use 'Find """" and Replace "" Command correctly for specific content control objects.

I looked up every single page in the internet, but I couldn´t find any specific commands which I can apply on content control objects. I appreciate all the answers:)

Sub InsertValuesinContentControls_ ()

Dim wdapp As Object
Dim wddoc As Object
Dim strdocname As String


On Error Resume Next

‘If my word doc is not open yet

Set wdapp = GetObject(, "Word.Application")

If Err.Number = 429 Then
Err.Clear
Set wdapp = CreateObject("Word.Application")
End If

wdapp.Visible = True

strdocname = "C:\Users\Userxx\File\NameofDocument.docm"

'activate the word doc
wdapp.Activate

Set wddoc = wdapp.Documents(strdocname)

If wddoc Is Nothing Then Set wddoc = wdapp.Documents.Open(strdocname)


'Now I copy single cells in my plain text controls which I established in Word

Worksheets("Generator").Range("F5").Copy
wddoc.ContentControls(1).Range.Paste

Worksheets("Generator").Range("B5").Copy
wddoc.ContentControls(2).Range.Paste

Worksheets("Generator").Range("A11").Copy
wddoc.ContentControls(3).Range.Paste

With wddoc.ContentControls(3)
.Replace What:=””””, Replacement:=””, Lookat:=xlPart, MatchCase:=False

End with


End Sub

sadly I can't comment yet, but did you try with: https://docs.microsoft.com/en-us/office/vba/word/concepts/customizing-word/finding-and-replacing-text-or-formatting

talking about

With ActiveDocument.Content.Find 
 .ClearFormatting 
 .Font.Bold = True 
 With .Replacement 
 .ClearFormatting 
 .Font.Bold = False 
 End With 
 .Execute FindText:="", ReplaceWith:="", _ 
 Format:=True, Replace:=wdReplaceAll 
End With

You shuld use .find on active document - word, then clear formating and set

.Execute FindText:="", ReplaceWith:="", _
Format:=True, Replace:=wdReplaceAll 

Hope I've helped. Have a great day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM