PDA

View Full Version : Microsoft Word Copy & Paste Macro



tessj
04-25-2013, 12:52 PM
I have a microsoft word document. In my document, some paragraphs contain the string <@@>. I want to write a macro that will search my document for the string <@@>. When it finds a paragraph which contains this string, it should copy the paragraph and then paste as hyperlink at the top of the document. It should repeat this process until it cannot find the string <@@>.

I tried this code but I keep getting the error message

Run-time error '4605'
This method or property is not available because the Clipboard is empty or not valid.

Sub SearchCopyAndPaste()
Dim exists As Boolean
Dim rngParagraphs As Range
Dim paragraphText As String

For Each p In ActiveDocument.Paragraphs
paragraphText = p.Range.text
exists = InStr(paragraphText, "<@@>") <> 0
If exists Then
Set rngParagraphs = ActiveDocument.Range( _
Start:=p.Range.Start, _
End:=p.Range.End)
rngParagraphs.Select
rngParagraphs.Copy
Selection.HomeKey Unit:=wdStory
Selection.PasteSpecial Link:=True, DataType:=wdPasteHyperlink
End If
Next p
End Sub

The problem is this line

Selection.PasteSpecial Link:=True, DataType:=wdPasteHyperlink

I don't get any error message when I replace it with this line, but I don't want an ordinary paste; I want to paste as hyperlink

Selection.PasteAndFormat (wdPasteDefault)

What am I doing wrong?

fumei
04-25-2013, 04:44 PM
Try something like:
Sub SearchCopyAndPaste()
Dim exists As Boolean
Dim r As Range
Dim oPara As Paragraph

For Each oPara In ActiveDocument.Paragraphs
exists = InStr(oPara.Range.Text, "<@@>") <> 0
If exists Then
Set r = oPara.Range
r.Copy
Selection.HomeKey Unit:=wdStory
Selection.PasteSpecial Link:=True, DataType:=wdPasteHyperlink
End If
Next oPara
End Sub

You DO want an "empty" paragraph at the top of the document to place the hyperlink lines.

tessj
04-25-2013, 11:38 PM
Thanks for your reply. I'm still getting the same error message. Do you think that the "empty" paragraph thing will stop this error message? How do I create an "empty" paragraph at the top of the document?

tessj
04-27-2013, 12:28 PM
It's okay now. I stopped getting the error message after I rebooted my computer.