Friday, April 05, 2019

Dusting off my Microsoft Word Programming Skills

When it comes to programmatically working with documents, I'm all about Google Docs, Sheets and Slides. But I recently found myself needing to step over to the Dark Side and write some code to interact with Microsoft Word. After a quick Visual Basic for Applications (VBA) refresher, I managed to eek out the code I needed. Surprisingly, I found myself impressed by the capabilities VBA offers. The API is massive and appears to let you automate nearly everything related to Word Docs. I suppose being an ancient and archaic incredibly mature product has its benefits.

In the interest of leaving breadcrumbs for myself, or for helping some other soul who finds themselves needing to write some Word VBA code, I'm publishing a bit of test code I wrote while tackling my project. It's CS 101 level stuff: iterate through the currently selected table and display the max and min numeric values found. But given how rusty my VBA skills are, working through this example was quite helpful.

Here's the code:

Sub TableInfo()
    minVal = 0
    maxValue = 0
    Dim t As Table
    If Selection.Tables.Count > 0 Then
        Set t = Selection.Tables(1)
        For Each r In t.Rows

            For Each c In r.Cells
                v = Left$(c, Len(c) - 2)
                v = Replace(v, "$", "")
                v = Replace(v, ",", "")
                If IsNumeric(v) Then
                    If Val(v) > maxValue Then
                        maxValue = Val(v)
                    End If
                    If minValue = 0 Or Val(v) < minValue Then
                        minValue = Val(v)
                    End If
                End If
        MsgBox "Min: $" & Format(minValue, "##,##") & ", Max: $" & Format(maxValue, "##,##")
        MsgBox "You're not currently on a table."
    End If
End Sub

And here's a screenshot, note the new toolbar item I added:

You can download the Word file containing the code here. Happy Hacking!

No comments:

Post a Comment