I am trying to work on a paste and merge formatting macro in microsoft word. I am constantly copying from a website and then pasting from that website into Word. Unfortunately, the website format is always:
Text
Citation
I want the format to be:
"Text." Citation.
My code currently is
Sub Paste_Citation()
' Paste_Citation Macro
On Error Resume Next
Selection.PasteAndFormat (wdFormatSurroundingFormattingWithEmphasis)
Selection.TypeBackspace
Selection.TypeBackspace
Selection.TypeText Text:="."
End Sub
I cannot figure out how to a) to not have a paragraph space between the text and the citation, b)put parentheses around the text. If the text does not have a period at the end, then format like "blah blah". Otherwise, "blah blah." and c) not include the text if the text only includes spaces and a period. I know that I need to do an if statement for c, but I am not very familiar with VBA in Word. Could someone walk through the process with me?
Edit #1
x = Selection.PasteAndFormat(wdFormatSurroundingFormattingWithEmphasis)
'trying to set x equal to the pasted formatted value
Dim Txt As String
Dim Cit As String
Txt = Split(x, Chr(182))
'trying to split the text based on the paragraph symbol
'I am confused on what I need to do from there
Edit #2
I have been working on it longer, and I think that I am pretty close. I figured out how to paste the info and merge the formats, as well as how to delete the paragraph break. My issue now is that I cannot figure out how to have it put quotations around the first paragraph, bring the cursor to the end of the paste, and add a period at the end.
Sub PasteCitation()
'Modified code from http://www.vbaexpress.com/forum/archive/index.php/t-46321.html
Application.ScreenUpdating = False
Dim Txt As Range
Set Txt = Selection.Range
Txt.PasteAndFormat (wdFormatSurroundingFormattingWithEmphasis)
With Txt.Find
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
'Replace single paragraph breaks with a space
.Text = "([!^13])([^13])([!^13])"
.Replacement.Text = "\1 \3"
.Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub
The red line of your programming should be to assign the downloaded 'Text' and 'Citation' to variables, say
Dim Txt As String
Dim Cit As String
Txt = "Whatever you scraped from tre website"
Cit = "Whatever else you scraped from the web"
With that accomplished you can start manipulating each of the strings and then place them in your document where you want, perhaps at the location of your current selection.
When you follow this method you may come to individual questions which can be answered quickly. Meanwhile, avoid the use of On Error Resume Next while you don't know what error might crop up and how you want to deal with it.
Related
I have several Word-Files containing old-style non-clickable UTF8-character checkboxes () and I want to replace them with real, clickable Checkboxes. They should be unchecked for and checked for another specified UTF8-character (which I do not know the number of right now).
I tried search and replace and copying from macros I've found online. I'm not a word user and this is a one-time-task, so I sadly do not have the time to learn VBA well enough to write such a thing as a macro.
I've found this online, but in the Macros-Window, I cannot even copy to "string to be searched".
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "string to be searched"
.Replacement.Text = "string to be replaced"
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
For Searching UTF=8 Character you have to search Unicodes like
U+2610 decimal ☐ Unchecked Checkbox
U+2611 decimal ☑ Checked Checkbox
U+2612 decimal ☒ Crossed Checkbox
Other like Unicode characters may also be explored for exactly what is it in your case. I tested with U+2610 decimal ☐ Unchecked Checkbox.
For replacement with FormField type of ComboBox I successfully used the code below
Sub TestFormFieldCB()
Dim Rng As Range, cb As FormField
ActiveDocument.Content.Select
With Selection.Find
.Text = ChrW(9744)
Do While .Execute
Set Rng = Selection.Range
ht = Rng.Font.SizeBi
Rng.Delete
Set cb = Rng.FormFields.Add(Rng, wdFieldFormCheckBox)
cb.CheckBox.Size = ht
Loop
End With
'ActiveDocument.Protect wdAllowOnlyFormFields
End Sub
The disadvantage of this type ComboBox is document is to be protected for the ComboBox to be clickable.
As Second option I tried with ActiveX Type ComboBox. It is easilyclickable even in unprotected mode but difficult to align and size with the text in the line. Also Somehow i could not use the same find Loop as in the above code and had to work around with some other way.
The final tested code is
Sub testActiveXCB()
Dim Rng As Range, cb As InlineShape, Fnd As Boolean
ActiveDocument.Content.Select
With Selection.Find
.Text = ChrW(9744)
.Execute
Do While Selection.Find.Found
Set Rng = Selection.Range
ht = Rng.Font.SizeBi
Rng.Delete
Set cb = Rng.InlineShapes.AddOLEControl(ClassType:="Forms.CheckBox.1")
Debug.Print cb.OLEFormat.Object.Name & "-" & cb.Height
cb.Width = cb.Height
cb.Width = ht
cb.OLEFormat.Object.Caption = ""
cb.OLEFormat.Object.PicturePosition = 2
'Use next Line when replacing Checked Unicode Char mat be U+2611 or U+2612
'cb.OLEFormat.Object.Value = True
ActiveDocument.Content.Select
Selection.Find.Execute
Loop
End With
End Sub
(All tests are carried out in Word 2007 only)
I request more answers and eager to learn from Word VBA experts regarding
Why the ActiveX Combo Box could not be inserted with the simple Find loop used in case of FormField type Combo Box?
How to effectively align Active X Combo Box with the text Line?
My goal is to create a TOC with two SEQIdentifiers in it.
It is described and answered HERE, though the given answer is manually configured, and I want to activate it with a macro.
Brief description
I have a sequential Figures throughout the document which can be gathered with Table of figures {SEQ \c "Figure"}.
The Figure structure is as follows:
Figure {STYLEREF 1 \s}-{SEQ Figure \*Arabic \s 1} - Result with 'Figure 1-1' for example.
The client request is to add "Point Figure", meaning between two figures: Figure 1-1 and Figure 1-2 the client can add Figure 1-1.A, Figure 1-1.B and so on.
Here is how I've initially created the sturcture:
Figure {STYLEREF 1 \s}-{SEQ Figure \*Arabic \c}.{SEQ PointFigure \* Alphabetic \s 1}.
The problem now is that I can not include both of them in a single Table of Figures.
Trying to implement the given answer:
So, my next approach was starting to implement the answer given in the link above.
The given answer by the way is as follow:
Bookmark the seq field with a special name - in the example it's tablea
refer to the reference by { SEQ Table \r { REF tablea } }
Here is my code followed by explanation and my problem:
Sub createPointFigure()
Dim rng As Range
Dim fld As Field
Dim searchText As String
Set rng = Selection.Range
rng.InsertAfter "Figure "
rng.Collapse wdCollapseEnd
Set fld = rng.Fields.Add(rng, wdFieldEmpty, "StyleRef 1 \s", False)
Set rng = fld.result
'Move focus after the inserted field
rng.Collapse wdCollapseEnd
rng.MoveStart wdCharacter, 1
rng.InsertAfter "-"
rng.Collapse wdCollapseEnd
rng.Fields.Add rng, wdFieldEmpty, "SEQ Figure \c", False
' select the entire inserted text
Selection.MoveRight wdWord, 4, wdExtend
searchText = Selection.Text
Set rng = Selection.Range
' Search for the specific figure in text
Selection.Collapse wdCollapseStart
Dim found As Boolean
found = False
While Not found And Selection.Start <> 1
findText searchText, False
For Each fld In Selection.Fields
If fld.Type = wdFieldSequence Then
' look for the original seq field
If InStr(1, fld.Code.Text, "\s 1", vbTextCompare) Then
found = True
Exit For
End If
End If
Next fld
If found Then
ActiveDocument.Bookmarks.Add Selection.Text, Selection
Else
' Collapse to the beginning and keep looking for the next one
Selection.Collapse wdCollapseStart
End If
Wend
End Sub
The findText method:
Sub findText(searchParam As String, forwardDirection)
With Selection.find
.ClearFormatting
.Text = searchParam
.Forward = forwardDirection
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
End Sub
Explanation:
Temporary create the closest Figure text
Search backward until finding the appropriate figure (keep looking if found a sequence field with \c).
Once found, create a new bookmark with the name
Construct the field as the answer suggests (Not implemented in the code)
Problems
Testing fails in the insert bookmark line:
ActiveDocument.Bookmarks.Add Selection.Text, Selection
Apparently, Bookmark cannot contain numbers and symbols in it.
How can I distinguish a reusable bookmark? For the next time I'll Create this Figure structure, I would like to reuse the same Bookmark.
All this work has huge overhead. Is there a simpler solution to accomplish my goal?
Thanks.
Thanks to #CindyMeister guidance, here is an elegant answer for my problem.
Point Figure configuration:
Figure {STYLEREF 1 \s}-{SEQ Figure \c}.{SEQ PointFigure \* Alphabetic \s 1}. Figure Text *Style Separator* {TC "{STYLEREF "Figure Title"}" \f F}
Table of Figures Configuration:
{TOC \f F \c "Figure"}
Remarks:
Figure style in my example is configured as "Figure Title"
The {TC} must be of a different style in order for STYLEREF to work.
For that I've used Style Separator (Ctrl + Alt + Return). Character style is another option I think.
All {} brackets in the code examples are Word Fields (Ctrl + F9)
I inserted the Point Figure text as an AutoText, which is added via Macro.
In order to achieve unique point numbering for each 'Figure 1-1' text, I've added a reset field before each one: {SEQ PointFigure \h \r 0}
I have several word documents to modify on a weekly basis that contain tables ranging from 1 x 6 up to 6 x 10 in size. All of the cells in all of the tables contain text, some of the cells contain text that is bold, some cells have mixed formatting(bold and standard), and the rest of the cells are standard.
I am trying to find code for a macro to change the background color in every cell that contains bold text, even it it also contains standard text.
This is pretty simple and I was able to find several different solutions for the this, but I run into the following issue in all code examples I have tried.
All of the examples I have tried will change the background color in all of the cells containing only bold text, but ignores the cells with mixed formatting(bold and standartd). I have tried several different ways to work around this but just don't have the knowledge to overcome the issue.
Here is a sample of the code I am using:
Sub Fill_Bold_Cell()
Dim myCell
For Each myCell In Selection.Tables(1).Range.Cells
If myCell.Range.Font.Bold = True Then
myCell.Range.Shading.BackgroundPatternColor = -603923969
End If
Next myCell
End Sub
Any help with this issue is greatly appreciated.
This pair of procedures should do the job.
Sub Fill_Bold_Cell()
Dim Tbl As Table
Dim myCell
For Each Tbl In ActiveDocument.Tables
For Each myCell In Tbl.Range.Cells
If FindBold(myCell.Range) Then
myCell.Range.Shading.BackgroundPatternColor = -603923969
End If
Next myCell
Next Tbl
End Sub
Private Function FindBold(Rng As Range) As Boolean
With Rng.Find
.ClearFormatting
.Font.Bold = True
.Text = ""
.Format = True
.Forward = True
.Wrap = wdFindStop
.Execute
FindBold = .Found
End With
End Function
As you see, I have kept your code almost unchanged. The critical part which was giving you a problem was moved into a separate function. In the way, the part which is good doesn't get contaminated by the part that isn't.
I trying to replace or search and add hyperlink to specyfy sentence in Word document. I try using this codes. Anyway code is changing only first finding word, not all in document:
Dim r As Word.Range
r = Globals.ThisAddIn.Application.ActiveDocument.Content
With r.Find
.ClearFormatting()
.Text = ("MyWordA MyWordB")
.MatchWholeWord = True
.Forward = True
.Execute()
'If .Found = True Then r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
Do While .Execute(Forward:=True) = True
r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
'r.Font.ColorIndex = Word.WdColorIndex.wdBlue 'works for all(?)
Loop
End With
Eaven when I want to find only single word in loop for, then code find first one:
doc = Globals.ThisAddIn.Application.ActiveDocument
Dim r As Word.Range = doc.Range
Dim ww As Word.Range
For Each ww In r.Words
If ww.Text = "MyWord" Then _
ww.Hyperlinks.Add(ww, "http:\\www.whatever", , "Displayed text")
Next
Anyone could tell me how I can search all text to replace/add hyperlinks to all text I was looking for?
The problem is that you keep finding the same text over and over again. Within your loop, after adding the hyperlink, you need to move the range after the added hyperlink. The simplest way to do this is to collapse the range by calling
r.Collapse(WdCollapseDirection.wdCollapseEnd)
To troubleshoot issues like this it is helpful to select the current range so that you can see what is going on.
Do While .Execute(Forward:=True) = True
' select range for troubleshooting
r.Select()
r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
' move the range after the link
r.Collapse(WdCollapseDirection.wdCollapseEnd)
Loop
I'm working on a Powerpoint slide, where I few texts are listed. I have to search for these texts in a Word Document which has a lot of Headings and Texts. After I find the title text, I need to copy the text under the Heading and paste in a new document.
Basically, the VBA coding has to be done in the Powerpoint VBA, with two documents in the background for searching text and pasting it in another.
I've opened the word doc. But searching the text in it and selecting it for copying to another document is what I've not been able to do. Kindly help me.
I see. The following is not exactly elegant since it uses Selection which I always try to avoid but it is the only way I know to achieve such a thing.
Disclaimer 1: this is made in Word VBA, so you will need a slight adaption, like set a reference to Word, use a wrdApp = New Word.Application object and declare doc and newdoc explicitely as Word.Document.
Disclaimer 2: Since you search for text instead of the respective heading, beware that this will find the first occurence of that text so you better not have the same text in several chapters. ;-)
Disclaimer 3: I cannot paste anymore! :-( My clipboard is set, it pastes elsewhere but I just cannot paste in here.
Code follows with first edit, hopefully in a minute...
Edit: yepp, pasting works again. :-)
Sub FindChapter()
Dim doc As Document, newdoc As Document
Dim startrange As Long, endrange As Long
Dim HeadingToFind As String, ChapterToFind As String
ChapterToFind = "zgasfdiukzfdggsdaf" 'just for testing
Set doc = ActiveDocument
Set newdoc = Documents.Add
doc.Activate
Selection.HomeKey unit:=wdStory
With Selection
With .Find
.ClearFormatting
.Text = ChapterToFind
.MatchWildcards = False
.MatchCase = True
.Execute
End With
If .Find.Found Then
'**********
'Find preceding heading to know where chapter starts
'**********
.Collapse wdCollapseStart
With .Find
.Text = ""
.Style = "Heading 1"
.Forward = False
.Execute
If Not .Found Then
MsgBox "Could not find chapter heading"
Exit Sub
End If
End With
.MoveDown Count:=1
.HomeKey unit:=wdLine
startrange = .Start
'*********
'Find next heading to know where chapter ends
'*********
.Find.Forward = True
.Find.Execute
.Collapse wdCollapseStart
.MoveUp Count:=1
.EndKey unit:=wdLine
endrange = .End
doc.Range(startrange, endrange).Copy
newdoc.Content.Paste
newdoc.SaveAs2 doc.Path & "\" & HeadingToFind & ".docx", wdFormatFlatXML
Else
MsgBox "Chapter not found"
End If
End With
End Sub
Edit: If you need to search for a "feature" that will be in some table in column 1 with the description in column 2 and you need that description in a new doc, try this:
Sub FindFeature()
Dim doc As Document, newdoc As Document
Dim FeatureToFind As String
Dim ro As Long, tbl As Table
FeatureToFind = "zgasfdiukzfdggsdaf" 'just for testing
Set doc = ActiveDocument
Set newdoc = Documents.Add
doc.Activate
Selection.HomeKey unit:=wdStory
With Selection
With .Find
.ClearFormatting
.Text = FeatureToFind
.MatchWildcards = False
.MatchCase = True
.Execute
End With
If .Find.Found Then
Set tbl = Selection.Tables(1)
ro = Selection.Cells(1).RowIndex
tbl.Cell(ro, 2).Range.Copy
newdoc.Range.Paste
End If
End With
End Sub
Edit: Slight adaptation so you can paste without overwriting existing content in newdoc:
Instead of newdoc.Range.Paste just use something along the line of this:
Dim ran As Range
Set ran = newdoc.Range
ran.Start = ran.End
ran.Paste