Docx brackets to comments (VBA)Thu 26 May 2016 by Eoin Travers
Microsoft Office is a necessary evil.
If you how to code, or even use a text editor, then almost everything that other people use Word for can be accomplished using markdown, LaTeX, pandoc, and some of the handy guides and tools produced by people like Kieran Healy and Sebastiaan Mathot. Sadly, there's still one point where you just need Word, or LibreOffice -- collaborating on papers.
Using markdown, and when exporting from LaTeX, I place comments and asides in my work within square brackets. [[ Some day I'll get around to posting some of this setup. ]] Wouldn't it be nice if I could convert these comments into proper comment bubbles in a Word document?
Sub BracketsToComment() ' Finds all text between square brackets "[[" and "]]" ' Turns it into a comment, attached to the previous word. ' Useful if you use [[ Comment ]] syntax in Markdown, or ' as part of something more sophisticated involving LaTeX or pandoc. Dim rng1 As range Dim rng2 As range Dim commentRange As range Dim match As String Dim cm As Comment Set rng1 = ActiveDocument.range ' Search for opening brackets Do While rng1.Find.Execute(FindText:="[[") = True ' Now search for closing ones Set rng2 = ActiveDocument.range(rng1.End, ActiveDocument.range.End) If rng2.Find.Execute(FindText:="]]") Then Set commentRange = ActiveDocument.range(rng1.End, rng2.Start) ' The range of our comment match = commentRange.Text Debug.Print (match) ' Optional ' Shift the range back a word (for making a comment box) With commentRange .Collapse Direction:=wdCollapseStart .Move Unit:=wdWord, Count:=-1 .Select End With ' Create the comment Set cm = commentRange.Comments.Add(range:=commentRange, Text:=match) cm.Author = "Your Name" cm.Initial = "YourInitials" End If Loop ' Finally, delete everything between square brackets - ' you don't need it any more Dim rng As Word.range Set rng = ActiveDocument.range With rng.Find .Text = "\[\[*\]\]" .Replacement.Text = "" .MatchWildcards = True .Execute Replace:=wdReplaceAll End With End Sub
I cobbled together this code from a few examples I found online, but the state of VBA documentation is so bad that I have over 60 tabs open to do this, and there's no way I'm going back over them all to find out what bits came from where. Finally, this code comes with absolutely no warrenty. Even if you don't mess around VBA, Word can and will eat your documents, and if that happens you'll never see them again. You've been warned.