In MS Word use macro to replace hyperlink text containing "#" and "!" - vba

In a Microsoft Word document, using a macro I want to change links like
https://www.library/#!/xyz to https://www.library2/xyz (where xyz indicates the specific resource and all other parts of these strings are constant).
The problem is that the "#!" characters in the original URL seem to terminate the string found by link.Address (and the "#!" is part of the original copied link -- not something I have a choice about).
My code:
Sub statelinks()
For Each link In ActiveDocument.Hyperlinks
MsgBox link.Address
Next
End Sub
For a document with one hyperlink https://www-clinicalkey-com.proxy.library.emory.edu/#!/content/book/3-s2.0-B9780323393041000038?scrollTo=%23hl0001812
the MsgBox shows https://www-clinicalkey-com.proxy.library.emory.edu/ (truncated immediately before the "#!").
How can I get the full URL?

Either you can use link.TextToDisplay - if it is identical to the address itself.
Or you can "hack" it a little bit joining address and subaddress - as Word vba assumes the # to be the divider for the subaddress
link.Address & "#" & link.SubAddress
This doesn't work if there are two #s in the URL ...

Related

Word VBA - format and re-link footnotes and endnotes in hyperlinks

I need to find footnote and endnote marks (in the body, to format them and re-link them) etc, in a macro I have written to clean up documents imported from the web.
My macro works fine, except where part of the find string is hyperlink display text and part is not.
Searching for ([a-z])([0-9]) (to locate endnote marks in the body, as they are not formatted as endnotes) does not find them because [0-9] is hyperlink display text and [a-z] is not.
My question here: how to search for [normal string] adjacent to [hyperlink display text string]?
If found, the next step is how to replace the hyperlink display text (format endnotes superscript, delete the para mark) keeping it in the hyperlink (I can work on that - maybe the subject of another question?)
You could, of course, simply convert your hyperlinks to superscripted numbers then use whatever other code you have to replace the superscripted numbers with endnotes.
Sub Demo()
Dim h As Long
With ActiveDocument
For h = .Hyperlinks.Count To 1 Step -1
With .Hyperlinks(h)
If IsNumeric(.TextToDisplay) = True Then
With .Range
If .Characters.First.Previous Like "[a-z]" Then
.Fields.Unlink
.Font.Reset
.Font.Superscript = True
End If
End With
End If
End With
Next
End With
End Sub
Depending on what you're doing, you could simply insert your endnoting code into the inner If ... End If construct in place of the font manipulations.

How to copy text from one document to another with same formatting?

I have this code to copy some text from one document to a new one.
For Each rng In docSource.SpellingErrors
docNew.Range.InsertAfter rng.text & vbCr
Next
Bus this is not copying the source format.
I'm trying with the following line but I get error
Expected function or variable
docNew.Range.InsertAfter rng.PasteAndFormat(wdPasteDefault) & vbCr
How can I do this? Thanks in advance.
Below some test text with errors.
When you create a Microsoft Word document for other people to read , it's important to spot and correct any speling mistakes
or gramatical errors you've made. You can let Word's spelling and grammmar
checkers suggest corrections automaticaly while you working , or you can check the spelling and gramar in the the file all
at once when you're finishes writing your document . Microsoft Word 2010 come with some dictionary of standardd grammar and spellings, but they are not comprehensive.
To transfer content from one Word document to another it's usually best to use Range.FormattedText rather than the Clipboard.
So something like this
Set docNewRange = docNew.Content
For Each rng In docSource.SpellingErrors
docNewRange.FormattedText = rng.FormattedText
docNewRange.Collapse wdCollapseEnd
docNewRange.InsertAfter vbCr
docNewRange.Collapse wdCollapseEnd
Next

Excel vba insert before bookmark does not give expected word order

I'm using the code below to open a new Word document and add a bookmark. I'm trying to insert multiple words a the bookmark 'MyBookmark' to form the sentence: "Once upon a time..."
I was expecting that by using InsertBefore the word would be inserted before the bookmark and I could add the next word after the first one, since the bookmark ends up at the end of the word. This is not what happens, instead the word gets added at the start of the sentence creating the sentence: "a time...upon Once"
How can I add words at the end of the sentence?
I've tried using InsertAfter, which had the same result. I don't want to change the order in which I add the words as this is not feasible on the larger scale I would like to implement this. The code below is an example of what I'd like to achieve in the actual implementation I'm opening a template saved as a dotx file.
Sub InsertBefore()
' Open Word document from template
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
wrdApp.Documents.Add
wrdApp.Activedocument.Bookmarks.Add Name:="MyBookmark"
' Insert text
wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "Once "
wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "upon "
wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "a time..."
End Sub
The easiest approach is to use the Selection object. You go there first and then you just start typing from there:
wrdApp.Activedocument.Bookmarks("MyBookmark").Range.Select
'Then from there on you just use the Selection object
wrdApp.Activedocument.ActiveWindow.Selection.TypeText("Once ")
wrdApp.Activedocument.ActiveWindow.Selection.TypeText("upon ")
wrdApp.Activedocument.ActiveWindow.Selection.TypeText("a time...")

Getting the previous Word in VBA using selection.previous wdword, 1 bug

I'm trying to write a macro to type the previous word at the cursor.
the problem is when i'm using "selection.previous wdword, 1" to get the previous character, it sometimes get the 2 previous characters and it seems like a bug. when i press "delete" button it works and it is very strange to me.
I'd glad if you help.
my ultimate goal is to create a calendar converter inside word using this code.
here is how i test it:
MsgBox Selection.previous(unit:=wdWord, Count:=1)
it is the same using next :
MsgBox Selection.Next(unit:=wdWord, Count:=1)
instead of next word, sometimes it returns the word after!
For example this is the text: during the flight on 21/3/1389
If the cursor is right after the 1389, msgbox selection.previous(1,1) would show "/"; if the cursor is after a space after 1389 it shows "1389". The problem is, I think, the space. My question is if there is any alternative to read the previous word instead of this command (Selection.previous(unit:=wdWord, Count:=1))
Word is not buggy - it's behaving as designed. Something has to tell Word where words start and end. When the cursor stands to the right of a space it's (quite logically) at the beginning of the next word. So going one word back is going to pick up 1389 instead of /.
You can work around this in your code. I'm sure there's more than one way to do it, but the following works for me in a quick test:
Sub GetPrevWord()
Dim rngSel As word.Range, rngPrev As word.Range
Set rngSel = Selection.Range
Set rngPrev = rngSel.Duplicate
rngPrev.MoveStart wdCharacter, -1
If Left(rngPrev.Text, 1) = " " Then
rngPrev.Collapse wdCollapseStart
End If
rngPrev.Select
MsgBox Selection.Previous(unit:=wdWord, Count:=1)
rngSel.Select
End Sub
What it's doing is using two Ranges: one to hold the original selection, the other to work with (rngPrev). rngPrev is extended backwards by one character and this character is evaluated. If it's a space then rngPrev is collapsed to its starting point. (Think of it like pressing the left arrow key of a selection.) In any case, rngPrev is selected and your MsgBox code is run. Finally, the original range is selected again.

how to create relative path in hyperlink excel ? (Word.Document.12)

I have two documents, one which has all the info and it is a word document, and another that is an excel document, that have just some highlights from the word document.
I want to create some links between some selected text in word and excel cells, so far the special past is doing a great job, and create link in this format
=Word.Document.12|'C:\Users\...\xxx.docx'!'!OLE_LINK9'
Now i want to copy both documents in my usb and past them in other computers, this where the problem is, i would have to do the special past all over again since the path is different now, what i though as a solution was to put the path to the word document in cell let say A1 and concatenate the formula above, something like
=Word.Document.12|A1!'!OLE_LINK9'
but it doesnt work, it throws an error message, can you please help me?
PS : I would like to avoid vba if possible
PS : I would like to avoid vba if possible
I have included both ways to do it since the question is tagged with Excel-VBA as well :)
Take your pick.
VBA Way
Is this what you are trying?
Sub Sample()
Dim objOle As OLEObject
'~~> Change this to the respective Sheet name
With ThisWorkbook.Sheets("Sheet1")
'~~> This is your embedded word object
Set objOle = .OLEObjects("Object 1")
'~~> Cell A1 has a path like C:\Temp\
objOle.SourceName = "Word.Document.12|" & .Range("A1").Value & "xxx.docx!'"
End With
End Sub
Non VBA Way
Create a named range and call it say Filepath. Set the formula to
="Word.Document.12|'" & Sheet1!$A$1 & "xxx.docx'!'"
Where Cell A1 will have the file path.
Next Select your word document and in the formula bar, type =Filepath and you are done.