MS Word VBA. Getting Source object from Footnote field - vba

In my document I must add footnotes to every formula i used. For example, I have some text with added Bibliography source
(something like "some very smart text [WrittenBySb]")
and I have formula
(for examle : E = mc2)
And after that formula I must add footnote contains source. I decided to write a macro that add footnote to formula with selected bibliography source:
Sub addFootnoteFromSelection()
Selection.MoveRight Unit:=wdCell 'my formula is in table - first row
'is null. second is actual formula and
'third contains actual formula's number
Selection.MoveRight Unit:=wdCell
Selection.MoveRight Unit:=wdCell
With Selection 'i want footnote mark to be in current
'formula's number
With .FootnoteOptions
.Location = wdBottomOfPage
.NumberingRule = wdRestartContinuous
.StartingNumber = 1
.NumberStyle = wdNoteNumberStyleArabic
End With
.Footnotes.Add Range:=Selection.Range, Reference:=""
End With
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Selection.Style = ActiveDocument.Styles("Numer wzoru")
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify
End Sub
And that works, but I want to have full source name (like in bibliography field), not a citation mark.
I write a function in vba that returns proper looking and formatted string from Source field:
Function stringFromSource(curField As Source) As String
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
xmlDoc.LoadXML curField.XML
authors = "": title = "": publish = "": city = "": year = "": periodic =
""
'authors
Set surname = xmlDoc.getElementsByTagName("b:Last")
Set name = xmlDoc.getElementsByTagName("b:First")
Dim l As Integer
l = 0
For Each el In surname
If el.Text = "" Then Exit For
authors = authors + (el.Text & " " & name(l).Text & " ")
l = l + 1
Next el
'title
Set titlex = xmlDoc.getElementsByTagName("b:Title")
For Each el In titlex
If el.Text = "" Then Exit For
title = title + (el.Text & " ")
Next el
'publisher
Set pubx = xmlDoc.getElementsByTagName("b:Publisher")
For Each el In pubx
publish = publish + (el.Text & " ")
Next el
'city
Set cityx = xmlDoc.getElementsByTagName("b:City")
If cityx.Length = 0 Then city = city + ("(brak miasta)" & " ")
For Each el In cityx
city = city + (el.Text & " ")
Next el
'year
Set yearx = xmlDoc.getElementsByTagName("b:Year")
If yearx.Length = 0 Then year = year + ("(brak roku wydania)" & " ")
For Each el In yearx
year = year + (el.Text & " ")
Next el
'periodical title
Set periodx = xmlDoc.getElementsByTagName("b:PeriodicalTitle")
For Each el In period
periodic = periodic + (el.Text & " ")
Next el
Dim outputString As String
outputString = author & "- " & title & ", " & publish & periodic & ", " &
year
stringFromSource = outputString
End Function
This function works as expected. But I want to loop through all footnotes and convert it to string using my function:
Sub convertAllFootnotes()
Dim ftn As Footnote
Dim oRng As Range
For Each ftn In ActiveDocument.Footnotes
Set oRng = Selection.Range
oRng.Start = oRng.Start - 1
oRng.End = oRng.End + 1
oRng.Select
oRng.Text = stringFromSource(ftn) 'i don't know how to get source object
'from footnote
Next ftn
End Sub
And that is my problem. I don't know how to get Source object from footnote (that has Source object in it, this is not a static string but copied proper Source field)

Related

Positioning a word at a specified position in word document VBA

I am trying to create a word document from excel. the document has specific text that doesnt vary with some data being entered from excel sheet which is being entered by means of an array. so whenever this variable data from sheet is entered, the word document adjust the lines as per the length of this variable. I want to keep the non variable part of my text to be sticking to its specific position regardeless of length of varying data being imported from sheets. Iam also struggling with adjusting the sentence length to match with the paper width. can you pls help
Sub ReminderWordDoc(strValue As String)
Dim wdApp As Word.Application
Set wdApp = CreateObject("Word.Application")
With wdApp
.Visible = True
.Activate
.Documents.Add
Dim objVar As Variant
objVar = Split(strValue, "~")
With .Selection
.ParagraphFormat.Alignment = wdAlignParagraphRight
.BoldRun 'Switch Bold on
.Font.Size = 12
.Font.Name = Arial
.Font.Underline = wdUnderlineSingle
.TypeText "IN LIEU OF MSG FORM"
.TypeParagraph 'Enter a new line
.ParagraphFormat.Alignment = wdAlignParagraphLeft
.TypeText "PRIORITY"
.BoldRun 'Switch Bold off
.TypeParagraph
.TypeText "FROM: HQ FORT DTG : 02" & vbCrLf
.TypeText "TO: " + UCase(objVar(1)) + " UNCLAS" & vbCrLf
.TypeText "INFO: " + UCase(objVar(2)) + " " + UCase(objVar(1)) & vbCrLf
.TypeText "--------------------------------------------------------------------------------------------------------------------" & vbCrLf
.TypeText " REMINDER NO 1 (.) COMPLAINT IN R/O " + UCase(objVar(3)) + " " + UCase(objVar(4)) + " " + UCase(objVar(2)) + _
"(.) REF OUR LETTER NO " + UCase(objVar(0)) + _
" DT ___________(___) COMMA _______(____) COMMA _______(____)(.) 'R' OF AS ASKED VIDE OUR LETTER UNDER REF IS STILL AWAITED (.) REQUEST FWD THE SAME BY _______ (___) (.) " & vbCrLf
.TypeText "--------------------------------------------------------------------------------------------------------------------" & vbCrLf
.TypeText "XYZ TELE:27676455 SR MGR" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf
.TypeText "CASE NO: " + UCase(objVar(0)) + " EXEC " & vbCrLf
.TypeText "DATED: " + UCase(Date) + " TOR____H" & vbCrLf
End With
End With
End Sub
Using tables is one way.
Sub ReminderWordDoc(strValue As String)
Dim wdApp As Word.Application
Set wdApp = CreateObject("Word.Application")
Dim wdDoc As Word.Document
With wdApp
.Visible = True
.Activate
End With
Set wdDoc = wdApp.Documents.Add
Dim objVar As Variant
objVar = Split(strValue, "~")
With wdApp.Selection
.ParagraphFormat.Alignment = wdAlignParagraphRight
.BoldRun 'Switch Bold on
.Font.Size = 12
.Font.Name = Arial
.Font.Underline = wdUnderlineSingle
.TypeText "IN LIEU OF MSG FORM"
.TypeParagraph 'Enter a new line
.ParagraphFormat.Alignment = wdAlignParagraphLeft
.TypeText "PRIORITY"
.BoldRun 'Switch Bold off
.TypeParagraph
End With
Dim t1 As Word.Table
Set t1 = wdDoc.Tables.Add(Range:=wdApp.Selection.Range, NumRows:=9, NumColumns:=2, _
DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitFixed)
t1.Borders.Enable = False
w = t1.Rows(1).Cells(1).Width * 2
w1 = w * 0.75
w2 = w * 0.25
For x = 1 To 9
With t1.Rows(x)
.Cells(1).Width = w1
.Cells(2).Width = w2
End With
Next x
t1.Rows(1).Cells(1).Range.Text = "FROM: HQ FORT"
t1.Rows(1).Cells(2).Range.Text = "DTG : 02"
t1.Rows(2).Cells(1).Range.Text = "TO: " + UCase(objVar(1))
t1.Rows(2).Cells(2).Range.Text = "UNCLAS"
t1.Rows(3).Cells(1).Range.Text = "INFO: " + UCase(objVar(2))
t1.Rows(3).Cells(2).Range.Text = UCase(objVar(1))
t1.Rows(4).Cells.Merge
t1.Rows(4).Cells(1).Range.Text = String(116, "-")
t1.Rows(5).Cells.Merge
t1.Rows(5).Cells(1).Range.Text = " REMINDER NO 1 (.) COMPLAINT IN R/O " + UCase(objVar(3)) + " " + UCase(objVar(4)) + " " + UCase(objVar(2)) + _
"(.) REF OUR LETTER NO " + UCase(objVar(0)) + _
" DT ___________(___) COMMA _______(____) COMMA _______(____)(.) 'R' OF AS ASKED VIDE OUR LETTER UNDER REF IS STILL AWAITED (.) REQUEST FWD THE SAME BY _______ (___) (.) "
t1.Rows(6).Cells.Merge
t1.Rows(6).Cells(1).Range.Text = String(116, "-")
t1.Rows(7).Cells(1).Split NumRows:=1, NumColumns:=2
t1.Rows(7).Cells(1).Range.Text = "XYZ"
t1.Rows(7).Cells(2).Range.Text = "TELE:27676455"
t1.Rows(7).Cells(3).Range.Text = "SR MGR"
t1.Rows(8).Cells(1).Range.Text = "CASE NO: " + UCase(objVar(0))
t1.Rows(8).Cells(2).Range.Text = "EXEC"
t1.Rows(9).Cells(1).Range.Text = "DATED: " + UCase(Date)
t1.Rows(9).Cells(2).Range.Text = "TOR____H"
End Sub

Sharepoint version history in document via vba?

Here is my problem:
Duplicate versions
I checked the version history on the Sharepoint site and it doesn't show any duplicates.
Here is the code im using:
Sub versionhistory()
'
' versionhistory Macro
On Error Resume Next
' On Error GoTo message
Dim dlvVersions As Office.DocumentLibraryVersions
Dim dlvVersion As Office.DocumentLibraryVersion
Dim strVersionInfo As String
Set dlvVersions = ThisDocument.DocumentLibraryVersions
'MsgBox ActiveDocument.Bookmarks.Count
Dim tbl As Word.Table
'Set tbl = ActiveDocument.Tables.Item(2)
Set tbl = ActiveDocument.Bookmarks("VersionTable").Range.Tables(1)
If dlvVersions.IsVersioningEnabled Then
strVersionInfo = "This document has " & dlvVersions.Count & " versions: " & vbCrLf
Call InsertVersionHistory(tbl, dlvVersions)
For Each dlvVersion In dlvVersions
strVersionInfo = strVersionInfo & _
" - Version #: " & dlvVersion.Index & vbCrLf & _
" - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
" - Modified on: " & dlvVersion.Modified & vbCrLf & _
" - Comments: " & dlvVersion.Comments & vbCrLf
Next
Else
strVersionInfo = "Versioning not enabled for this document."
End If
'MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
Set dlvVersion = Nothing
Set dlvVersions = Nothing
Call GetUserName
'message:
'MsgBox Err.Description
MsgBox ("Insert Version Number in the Header and type a Title in the [Insert Title here] on the front page. It will be automatically updated in the footer." & vbNewLine & vbNewLine & "Do Not Type in the Review and Version tables.")
End Sub
Private Function InsertVersionHistory(oVerTbl As Word.Table, oVersions As Office.DocumentLibraryVersions)
Dim rowIndex As Integer
Dim oVersion As Office.DocumentLibraryVersion
Dim oNewRow As Row
'test
Dim versionIndex As Integer
For rowIndex = 2 To oVerTbl.Rows.Count
oVerTbl.Rows.Item(2).Delete
Next rowIndex
rowIndex = 1
'test
versionIndex = oVersions.Count
For Each oVersion In oVersions
If (rowIndex > 5) Then
Return
End If
rowIndex = rowIndex + 1
oVerTbl.Rows.Add
Set oNewRow = oVerTbl.Rows(oVerTbl.Rows.Count)
oNewRow.Shading.BackgroundPatternColor = wdColorWhite
oNewRow.Range.Font.TextColor = wdBlack
oNewRow.Range.Font.Name = "Tahoma"
oNewRow.Range.Font.Bold = False
oNewRow.Range.Font.Size = 12
oNewRow.Range.ParagraphFormat.SpaceAfter = 4
With oNewRow.Cells(1)
'.Range.Text = oVersion.Index
.Range.Text = versionIndex
End With
With oNewRow.Cells(2)
.Range.Text = FormUserFullName(GetUserFullName(oVersion.ModifiedBy))
End With
With oNewRow.Cells(3)
.Range.Text = oVersion.Modified
End With
With oNewRow.Cells(4)
.Range.Text = oVersion.Comments
End With
versionIndex = versionIndex - 1
Next
Set oVersion = Nothing
End Function
Function GetUserFullName(userName As String) As String
Dim WSHnet, UserDomain, objUser
Set WSHnet = CreateObject("WScript.Network")
'UserDomain = WSHnet.UserDomain
'Set objUser = GetObject("WinNT://" & UserDomain & "/" & userName & ",user")
userName = Replace(userName, "\", "/")
Set objUser = GetObject("WinNT://" & userName & ",user")
'MsgBox objUser.FullName
GetUserFullName = objUser.FullName
End Function
Function FormUserFullName(userName As String) As String
Dim arrUserName As Variant
Dim changedUserName As String
arrUserName = Split(userName, ",")
Dim length As Integer
length = UBound(arrUserName) - LBound(arrUserName) + 1
If length >= 2 Then
changedUserName = arrUserName(1) & " " & arrUserName(0)
Else
changedUserName = userName
End If
FormUserFullName = changedUserName
End Function
Private Function GetUserName()
Dim userName As String
userName = ActiveDocument.BuiltInDocumentProperties("Author")
ActiveDocument.BuiltInDocumentProperties("Author") = FormUserFullName(userName)
End Function
I know this is old, but I was looking for the same thing and found this article. I'm still trying it out, but wanted to share before I got distracted with my real job.
From: SixSigmaGuy on microsoft.public.sharepoint.development-and-programming.narkive.com/...
Wanted to share my findings, so far. Surprisingly, I could not find
anything in the SharePoint Designer object/class that supported versions,
but the Office, Word, Excel, and PowerPoint objects do support it.. It
wasn't easy to find, but once I found it, it works great, as long as the
file in the document library is one of the Office documents.
Here's some sample code, written in Excel VBA, showing how to get the
version information for a paritcular SharePoint Document Library file
created in Excel:
Public viRow As Long
Function fCheckVersions(stFilename As String) As Boolean
' stFilename is the full URL to a document in a Document Library.
'
Dim wb As Excel.Workbook
Dim dlvVersions As Office.DocumentLibraryVersions
Dim dlvVersion As Office.DocumentLibraryVersion
Dim stExtension As String
Dim iPosExt As Long
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 1) = stFilename
If Workbooks.CanCheckOut(stFilename) = True Then
Set wb = Workbooks.Open(stFilename, , True)
Set dlvVersions = wb.DocumentLibraryVersions
If dlvVersions.IsVersioningEnabled = True Then
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 3) = "Num
Versions = " & dlvVersions.Count
For Each dlvVersion In dlvVersions
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 4) = "Version: " & dlvVersion.Index
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 5) = "Modified Date: " & dlvVersion.Modified
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 6) = "Modified by: " & dlvVersion.ModifiedBy
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 7) = "Comments: " & dlvVersion.Comments
viRow = viRow + 1
Next dlvVersion
End If
wb.Close False
End If
Set wb = Nothing
DoEvents
End Function`
Fortunately, I discovered that Excel can open non-Excel files in most
cases. I.e., I can, for example, open a jpg file in Excel and use the
dlvVersions collection for that file.

Getting Source object from footnote (word vba)

I create footnotes which contains Source objects (a Source object is a single object from Sources list, from which I create Bibliography)
All I want to do is to loop through all footnotes and get XML file from each Source object to retrieve information about Author and so on.
I have problem with getting Source object from footnotes. I tried to select footnote and retrieve this object from selection but nothing works. Maybe You guys have a proper way to retrieve "parent object" from another object in vba?
Sub convertAllFootnotes()
Dim ftn As Footnote
Dim oRng As Range
For Each ftn In ActiveDocument.Footnotes
Set oRng = Selection.Range
oRng.Start = oRng.Start - 1
oRng.End = oRng.End + 1
oRng.Select
oRng.Text = stringFromSource(ftn) 'i don't know how to get source object
'from footnote
Next ftn
End Sub
string from source function (which works properly, i must pass to it Surce object)
Function stringFromSource(curField As Source) As String
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
xmlDoc.LoadXML curField.XML
authors = "": title = "": publish = "": city = "": year = "": periodic =
""
'authors
Set surname = xmlDoc.getElementsByTagName("b:Last")
Set name = xmlDoc.getElementsByTagName("b:First")
Dim l As Integer
l = 0
For Each el In surname
If el.Text = "" Then Exit For
authors = authors + (el.Text & " " & name(l).Text & " ")
l = l + 1
Next el
'title
Set titlex = xmlDoc.getElementsByTagName("b:Title")
For Each el In titlex
If el.Text = "" Then Exit For
title = title + (el.Text & " ")
Next el
'publisher
Set pubx = xmlDoc.getElementsByTagName("b:Publisher")
For Each el In pubx
publish = publish + (el.Text & " ")
Next el
'city
Set cityx = xmlDoc.getElementsByTagName("b:City")
If cityx.Length = 0 Then city = city + ("(brak miasta)" & " ")
For Each el In cityx
city = city + (el.Text & " ")
Next el
'year
Set yearx = xmlDoc.getElementsByTagName("b:Year")
If yearx.Length = 0 Then year = year + ("(brak roku wydania)" & " ")
For Each el In yearx
year = year + (el.Text & " ")
Next el
'periodical title
Set periodx = xmlDoc.getElementsByTagName("b:PeriodicalTitle")
For Each el In period
periodic = periodic + (el.Text & " ")
Next el
Dim outputString As String
outputString = author & "- " & title & ", " & publish & periodic & ", " &
year
stringFromSource = outputString
End Function

Word VBA discrepancy between Instr() actual starting position of a string

I am using regex to find all pattern matches in a Word doc, which I will then manipulate.
The file I'm searching is ~330 pages long and includes copy/pasted emails. My problem is that when I use InStr(startPos, objRange.Text, match.submatches(0)) to find the starting position of each match, the result is actually offset by some amount. For the document in its original state, that offset happened to be 324 characters.
On a hunch, I decided to remove all the hyperlinks in the document to see what that would do. The RemoveHyperlinks sub found and removed 24 hyperlinks, after which the Instr() return value was off by only 20 characters (so that subtracting the magic number matchStart = matchStart - 1 - 20 gives the correct starting position). Obviously I want to avoid all magic numbers, but I cannot figure out where the last 20 characters are coming from.
I tried unlinking all fields, but there weren't any to unlink after the hyperlinks were removed.
Any thoughts on why
matchStart = InStr(startPos, objRange.Text, match.submatches(0))
matchEnd = matchStart + Len(match.submatches(0))
Set subRange0 = objDoc.Range(matchStart, matchEnd)
give me subRange0.Text different from match.submatches(0)? Or where the other hidden characters may be found (to be removed)?
Sub FixHighlightedText()
Dim objDoc As Document
Dim objRange As Range, subRange0 As Range
Dim matchStart As Long, matchEnd As Long, startPos As Long
Dim regex As Object
Dim matches
Set objDoc = ActiveDocument
Set objRange = objDoc.Range(0, objDoc.Content.End)
startPos = 1
Set regex = CreateObject("VBScript.RegExp")
Call RemoveHyperlinks
With regex
.Pattern = "((\([a-zA-Z]*?[-]?Time:.*?\})[a-zA-Z0-9]{0,3})"
.Global = True
End With
If regex.test(objRange.Text) Then
Set matches = regex.Execute(objRange.Text)
Debug.Print "Document has " & matches.Count & " matches"
Debug.Print "Document range is " & objRange.Start & " to " & objRange.End
Debug.Print "FirstIndex = " & matches(0).FirstIndex
For Each match In matches
matchStart = InStr(startPos, objRange.Text, match.submatches(0))
startPos = matchStart + Len(match.submatches(0))
If matchStart > 0 Then
matchStart = matchStart - 1
matchEnd = matchStart + Len(match.submatches(0))
Set subRange0 = objDoc.Range(matchStart, matchEnd)
Debug.Print "Match starts at " & matchStart & " and ends at " & (matchStart + Len(match.submatches(1)))
Debug.Print " match0 text = " & match.submatches(0)
Debug.Print " subrange0 text = " & subRange0.Text
Else
Debug.Print "Match mysteriously not found in text"
End If
Next match
Else
Debug.Print "No regex matches"
End If
End Sub
Sub RemoveHyperlinks()
Dim link, cnt As Long, linkRange As Range, i As Long
cnt = 0
For i = ActiveDocument.Hyperlinks.Count To 1 Step -1
With ActiveDocument.Hyperlinks(i)
.TextToDisplay = .TextToDisplay & " (" & .Address & ")"
Set linkRange = .Range
End With
ActiveDocument.Hyperlinks(i).Delete
With linkRange.Font
.Underline = wdUnderlineNone
.ColorIndex = wdAuto
End With
cnt = cnt + 1
Next i
Debug.Print "Removed " & cnt & " link(s)"
End Sub
Sub RemoveFields()
Dim cnt As Long, i As Long
cnt = 0
For i = ActiveDocument.Fields.Count To 1 Step -1
ActiveDocument.Fields(i).Unlink
cnt = cnt + 1
Next i
Debug.Print "Removed " & cnt & " field(s)"
End Sub
I ended up finding the hint to my answer in the selected answer to this question: vbscript: replace text in activedocument with hyperlink.
Essentially, Instr() does not play well with the WYSIWYG feature of Word, but the Find method will give selections with the proper ranges. No need to remove hyperlinks nor worry about other mysterious, hidden text.
The code would look like:
Sub FixHighlightedText()
Dim objDoc As Document
Dim objRange As Range
Dim startPos As Long
Dim regex As Object
Dim matches
Set objDoc = ActiveDocument
Set objRange = objDoc.Range
startPos = 1
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "((\([a-zA-Z]*?[-]?Time:.*?\})[a-zA-Z0-9]{0,3})"
.Global = True
End With
If regex.test(objRange.Text) Then
Set matches = regex.Execute(objRange.Text)
Debug.Print "Document has " & matches.Count & " matches"
Debug.Print "Document range is " & objRange.Start & " to " & objRange.End
Debug.Print "FirstIndex = " & matches(0).FirstIndex
For Each match In matches
Set objRange = objDoc.Range(startPos, objDoc.Content.End)
With objRange.Find
.Text = match.submatches(0)
.MatchWholeWord = True
.MatchCase = True
.Wrap = wdFindStop
.Execute
End With
startPos = objRange.End
Debug.Print "Match starts at " & objRange.Start & " and ends at " & objRange.End
Debug.Print " match0 text = " & match.submatches(0)
Debug.Print " subrange text = " & objRange.Text
Next match
Else
Debug.Print "No regex matches"
End If
End Sub

Get heading number from previous heading

This Word macro written by Paul Beverley adds a comment to the document and inserts the page and line numbers.
Sub CommentAdd()
' Version 20.02.12
' Add a comment
' Ctrl-Alt-#
attrib1 = "PB: "
attrib2 = "PB: "
postText = ""
keepPaneOpen = False
addPageNum1 = True
addLineNum1 = True
addPageNum2 = True
addLineNum2 = True
highlightTheText = False
textHighlightColour = wdYellow
colourTheText = False
textColour = wdColorBlue
Set rng = Selection.Range
rng.Collapse wdCollapseEnd
rng.MoveEnd , 1
pageNum = rng.Information(wdActiveEndAdjustedPageNumber) ' <<<<<----- This line
lineNum = rng.Information(wdFirstCharacterLineNumber)
If Selection.End <> Selection.Start Then
If Right(Selection, 1) = Chr(32) Then Selection.MoveEnd wdCharacter, -1
Set rng1 = Selection.Range
' Either highlight it ...
myTrack = ActiveDocument.TrackRevisions
ActiveDocument.TrackRevisions = False
If highlightTheText = True Then Selection.Range.HighlightColorIndex _
= textHighlightColour
' And/or change the text colour to red
If colourTheText = True Then Selection.Font.Color = textColour
ActiveDocument.TrackRevisions = myTrack
' Now add the comment
Selection.Comments.Add Range:=Selection.Range
If addPageNum1 = True Then attrib1 = attrib1 & "(p. " & _
pageNum & ") "
If addLineNum1 = True Then attrib1 = attrib1 & "(line " & _
lineNum & ") "
Selection.TypeText Text:=attrib1 & ChrW(8216) & ChrW(8217)
' Move back to between the close and open quotes
Selection.MoveEnd wdCharacter, -1
' 'Paste' in a copy of the selected text
Set rng2 = Selection.Range
rng2.FormattedText = rng1.FormattedText
rng2.Revisions.AcceptAll
rng2.Start = rng2.End - 1
If rng2.Text = Chr(13) Then rng2.Delete
' Move back past the close quote
rng2.Start = rng2.End + 1
If postText > "" Then
rng2.InsertAfter Text:=postText
Else
rng2.InsertAfter Text:=" " & ChrW(8211) & " "
End If
If keepPaneOpen = False Then ActiveWindow.ActivePane.Close
Else
cmntText = attrib2
If addPageNum2 = True Then cmntText = cmntText & _ ' <<<<<----- And this I guess
"(p. " & pageNum & ") "
If addLineNum2 = True Then cmntText = cmntText & _
"(line " & lineNum & ") "
Selection.MoveEnd , 1
Selection.Comments.Add Range:=Selection.Range, Text:=cmntText
End If
End Sub
I have been trying (in Word's VB Editor) to tweak the highlighted line (here followed by '<<<<----- This line') to have the macro get and write the number of the previous header instead of the page number. The idea is that if the user selects a string, the macro looks for the closest header level (h1, h2, h3, etc.) above it and writes its number.
Example:
1 This is header1 > If the selected string happens to be under this header, then write "1"
1.2 This is header2 > If the selected string happens to be under this header, then write "1.2"
1.2.1 This is header3 > If the selected string happens to be under this header, then write "1.2.1"
So far I have tried these two options to replace the bolded line, to no avail (I have renamed "pageNum" to "headerNum"):
' Option 1
headerNum = ActiveDocument.Styles("Heading")
' Option 2
headerNum = Selection.range = Styles("Heading")
What am I doing wrong?
Any help will be highly appreciated!!!