Word UserForm VBA: Hyperlink from Bookmark - vba

I am able to populate a bookmarked location on a Word Document from user input via a UserForm.
What I would like to do is convert the text entered into a Hyperlink.
The following snippit of code was used to insert the text into the appropriate location:
Private Sub CommandButton1_Click()
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL
Me.Repaint
'Update the fields to populate the references of the bookmarks
UpdateAllFields
UserForm1.Hide
End Sub
I tried the following which did not work:
Private Sub CommandButton1_Click()
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
Hyperlinks.Add(ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL)
Me.Repaint
'Update the fields to populate the references of the bookmarks
UpdateAllFields
UserForm1.Hide
End Sub
Any advice will be much appreciated
Thanks in advance

Hyperlinks.Add(ActiveDocument.Bookmarks.Add "benchmark", benchmarkURL)
There are at least two things wrong with this line, possibly more depending on what it is you want the hyperlink to link to.
You have omitted the parent object for the Hyperlink which should be ActiveDocument.
There should not be any brackets as the return value of
Hyperlinks.Add is not being assigned to anything.
You can find further info here: https://msdn.microsoft.com/en-us/library/office/ff837214(v=office.15).aspx

I found a better solution. For those that need, it is posted below:
'URL of Benchmark Data
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Hyperlinks.Add Anchor:=benchmarkURL, Address:= _
benchmarkURL.Text, SubAddress:="", ScreenTip:="", TextToDisplay:= _
"Benchmark Data"

Just to provide some further description to Jame's answer.
'URL of Benchmark Data
Dim benchmarkURL As Range
Set benchmarkURL = ActiveDocument.Bookmarks("benchmark").Range
benchmarkURL.Text = Me.benchmarkURLTextBox.Value
ActiveDocument.Hyperlinks.Add Anchor:=benchmarkURL, Address:=benchmarkURL.Text, SubAddress:="", ScreenTip:="", TextToDisplay:="Benchmark Data"
means put this information in.
'URL of Benchmark Data
ActiveDocument.Hyperlinks.Add Anchor:=<<Where link will display>>, Address:= <<Where the link will go to>>, SubAddress:="", ScreenTip:="", TextToDisplay:="<<what the link text should say"
This is my working version. In my instance I take text like this AC-2 in a table cell and make a bookmark with AC2. One table with AC-2 clicks to another table with AC-2 that is bookmarked.
'/////////////
Set benchmarkURL = oDoc.Bookmarks(strText2).Range
With oDoc.Tables(r).Cell(i, 1)
.Range.Hyperlinks.Add Anchor:=oDoc.Tables(r).Cell(i, 1).Range, Address:="", SubAddress:=strText2, ScreenTip:="", TextToDisplay:=strText
End With

Related

Making links to Places in this document work in vba

I'm trying to make a VBA script that will take all the headings in a document and make a table of contents out of them, with hyperlinks to each of the headings. The headings are all found, parsed and all the hyperlinks are made, however they don't correctly reach their destination which is a place within the document. The default 'create hyperlink to Place in this document' code looks like this:
Selection.Range.Hyperlinks(1).Range.Fields(1).Result.Select
Selection.Range.Hyperlinks(1).Delete
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:="_Test_Heading"
Selection.Collapse Direction:=wdCollapseEnd
This is the code that you would get if you recorded a macro while using the 'Edit hyperlink' window.
Edit hyperlink window
The address field where normally there would be a URL is empty, while the subaddress field is filled by the name of the header with underscores.
I think the problem is that Word defaults to 'Existing file or web page' rather than 'Place in this document', even if 'Place in this document' were specified prior. If I switch the mode of a link to 'Place in this document' without changing the subaddress or anything else, it works - but having to go and do that for each link defeats the purpose of the script. I've been looking all over for a way to express 'Place in this document' in VBA but haven't found anything. Tried bookmarks as an alternative and that didn't work either. Any help would be appreciated.
I found a workaround using cross-referencing. In case it helps anyone in the future:
Private Function GetLevel(strItem As String) As Integer
Dim strTemp As String
Dim strOriginal As String
Dim longDiff As Integer
strOriginal = RTrim$(strItem)
strTemp = LTrim$(strOriginal)
longDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (longDiff / 2) + 1
End Function
Sub TableofContents()
Dim i As Integer
Dim AllHeadings As Variant
AllHeadings = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)
Selection.HomeKey Unit:=wdStory
Selection.HomeKey Unit:=wdLine
For i = LBound(AllHeadings) To UBound(AllHeadings)
strtext = Trim$(AllHeadings(i))
Level = GetLevel(CStr(AllHeadings(i)))
If Level = 2 Then
Selection.InsertCrossReference ReferenceType:="Heading", ReferenceKind:= _
wdContentText, ReferenceItem:=i, InsertAsHyperlink:=True, _
IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
Selection.TypeParagraph
End If
Next
End sub
The first function gets the level of the heading.
The second part moves to the top of the document and starts inserting cross-references to the headings that I want (in this case I want it to be = 2).

How to display quick part > document property in word using macro?

I have two custom column in quick part mapped from sharepoint edit template.
DocSigner and DSigneromment
Now i have write macro code in word for get all builtinproperties and custom properties. I am able to get all built in document properties like Author ,Title and all but not able to get that custom column using "CustomDocumentProperties"..
Here is my macro code..
Sub ListAllProperties()
Dim rngDoc As Range
Dim proDoc As DocumentProperty
Set rngDoc = ActiveDocument.Content
rngDoc.Collapse Direction:=wdCollapseEnd
For Each proDoc In ActiveDocument.CustomDocumentProperties
With rngDoc
.InsertParagraphAfter
.InsertAfter proDoc.Name & "= "
On Error Resume Next
.InsertAfter proDoc.Value
End With
Next
End Sub
So any code changes that i can get all document property from quick part.
To get the values of properties coming from custom SharePoint columns, use the Document's ContentTypeProperties collection.
#bibadia Thanks a lot for your contribution
Here is finally i have tried for custom property and it works...
Sub ListContentTypeProperty()
Dim signer As String
signer = ActiveDocument.ContentTypeProperties.Item("DocSigner")
MsgBox signer
End Sub

Insert Symbol in Text box VBA Word

I have the following code to insert a textbox into a word document:
Sub mark()
Dim Box As Shape
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=20, Top:=20, Width:=20, Height:=20)
Box.TextFrame.TextRange.Text = "tick"
End Sub
The text inside the texbox needs to be:
Selection.InsertSymbol Font:="Wingdings", CharacterNumber:=-3844, Unicode :=True
I see you've found an answer, but there's a more optimal way to use the method you found. Since it's not possible to format code nicely in Comments I'm writing it up in the Answer space for you (and others who might have the same question). Also, the site prefers the useful information to be in an "Answer" since Comments tend to be over-looked or deleted...
In order to insert content from the Insert Symbol dialog box, use the InsertSymbol method, which applies to either the Range or the Selection`object.
Using the Rangeobject is always the preferred approach. In order to get a Range object for the text box content, adjust your code something like this:
Sub mark()
Dim Box as Word.Shape
Dim rngBox as Word.Range
Set Box = ActiveDocument.Shapes.AddTextBox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=20, Top:=20, Width:=20, Height:=20, _
Set rngBox = Box.TextFrame.TextRange
rngBox.Text = "tick"
rngBox.Collapse wdCollapseEnd 'focus at end of Range
rngBox.InsertSymbol Font:="Wingdings", CharacterNumber:=-3844, Unicode:=True
End Sub
The Collapse method allows you to continue adding text (optionally with formatting) for as long as you require...

running multiple macros when cells in a range are changed

bear with me, as I am a complete vba newbie and wrapping my head around what I already have has already taken me much longer than I care to admit.
I have a workbook with one master list "ITEMS" and several (up to 15) sub-tabs that grab information from the ITEMS sheet. I've been able to make this happen using buttons on each sub sheet which call this code:
Private Sub getNELL_Click()
Sheets("ITEMS").Range("A1:K400").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("ITEMS").Range("O1:O2"), CopyToRange:=Range("A1:K1") _
, Unique:=False
End Sub
This code successfully grabs each relevant row into the sheet each time I click the button, where each getX has a different name/criteria range (getRILEY, getELLE etc.)
But what I'm looking to do next is to have these macros run automatically when any cell in the G column of the ITEMS sheet is changed. In plain text, what I need is:
When [Any Cell in Column G] in Sheet("ITEMS") is changed
Run getNELL, getRiley, getELLE (x15 different macros)
here's my file with all the sheet (sic) in it.
EDIT:
and it's done!
moving the macros to a module instead of in each individual sheet, making them public and removing the _Click, along with the following code worked the magic I needed.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("G2:G400")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
getNELL
getMIKA
getRILEY
getJANNA
getWOO
getELLE
getMK
getLAURA
getFLIPSE
getJENN
getCRIS
End If
End Sub
First off, use this link as a resource for triggering an event when cells change. That's usually just in the subroutine declaration.
For the code, change all of your private subs to public subs by replacing "private" with "public". Then in your subroutine list the subroutines to call:
>
Subx
Suby
Subz
end sub
Sorry the answer isn't super detailed as I am typing from my phone. Also, those sub examples should each be on their own line. I can't seem to change that on here.
you have already created filter criteria in ITEM sheet (grey highlighted)
so create one mapping for what sheet needs what criteria range in INDEX sheet
e.g.
SheetName Criteria Mapping
nell O1:O2
mika P1:P2
riley Q1:Q2
janna R1:R2
woo S1:S2
elle O3:O4
mk P3:P4
laura Q3:Q4
flipse R3:R4
jenn S3:S4
cris O5:O6
Add this code in a Module
Public Sub pGet_Data(ByVal SheetName As Worksheet, ByVal CriteriaRng As Range)
ThisWorkbook.Worksheets("ITEMS").Range("A1:K400").AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=CriteriaRng, _
CopyToRange:=SheetName.Range("A1:K1"), _
Unique:=False
End Sub
And in Thisworkbook Module add given code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim rngCriteriaRange As Range
Dim rngOneMap As Range
Dim wksSheet As Worksheet
If Sh.Name = "ITEMS" And Target.Column = 7 Then
Set rngCriteriaRange = Sh.Range("W6:X16") '<--you can make it dynamic
For Each rngOneMap In rngCriteriaRange.Rows
Set wksSheet = ThisWorkbook.Worksheets(rngOneMap.Cells(1, 1).Value)
Application.StatusBar = "Updating [" & wksSheet & "] Sheet"
Call pGet_Data(wksSheet, wksSheet.Range(rngOneMap.Cells(1, 2).Value))
Next rngOneMap
End If
MsgBox "Sheets has been updated.", vbOKOnly, "Be Happy..."
ClearMemory:
Set rngCriteriaRange = Nothing
Set rngOneMap = Nothing
Set wksSheet = Nothing
End Sub
I think this will resolve what you are looking for... :)

Excel VBA: clear items in pivot table

I am new to VBA...
I am trying to write a macro that will clear all the selections within a pivot table filter named "Product Family" and select only the item whose name is contained in cell "B33". I am referencing the pivot table in one sheet "sheet8" and trying to change a graph on "Dashboard".
Here is the code...
Sub thisisalsotemp()
'
' thisisalsotemp Macro
'
'
Sheets("Dashboard").Select
ActiveSheet.ChartObjects("Chart 1").Activate
Sheet8.PivotTables("capbylp").PivotFields("Product Family").PivotFields.ClearAllFilters
With Sheet8.PivotTables("capbylp").PivotFields("Product Family")
.PivotItems(Range("B33")).Visible = True
End With
End Sub
The error is in the following line:
Sheet8.PivotTables("capbylp").PivotFields("Product Family").PivotFields.ClearAllFilters
The error message is:
Object doesn't support this property or method
#SeanCheshire: Thanks for the help. I feel this is much closer to what I want. However, I couldnt get it to work. I played around with it a little bit and am closer. here is what i have...
Sub thisisalsotemp2()
Sheets("Dashboard").Select
Sheet8.PivotTables("capbylp").PivotFields("Product Family") = Range("B33")
End Sub
Error 1004 reads: unable to set the pivotfields property of the pivottable class
in the line: Sheet8.PivotTables("capbylp").PivotFields("Product Family") = Range("B33")
you need to set CurrentPage (and you shouldn't need to clear it first).
Using what is shown in your code, I would have something like:
Sheet8.PivotTables("capbylp").PivotFields("Product Family"). _
PivotFields("MyPivotField").CurrentPage = Range("B33").Value
(broken into 2 lines for readability)
This is slightly related; I wanted to clear multiple-selections whenever the user makes them. Apparently, setting the VisibleItemsList can do that.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim xPF As PivotField
Dim nms As Variant
nms = Array("Calculation", _
"Rate Type", _
"xx Hierarchy")
Set xPT = Application.ActiveSheet.PivotTables(1)
For Each xPF In xPT.PageFields
For Each nm In nms
If xPF.Name Like "*" & nm & "*" Then
If UBound(xPF.VisibleItemsList) > 1 Then
xPF.VisibleItemsList = Array("")
End If
End If
Next nm
Next xPF
End Sub