Quantcast
Channel: Microsoft Office – The Happy Coder
Viewing all articles
Browse latest Browse all 16

Word: Insert Fields with VBA

$
0
0

microsoft-clip-art-computerI have written quite a bit about SQL, C#, Visual Basic and Excel but until now I haven’t covered other Microsoft products. Today I am writing about some Microsoft Word macros I wrote recently that ended up being huge time-savers.

I needed to create a couple mail-merge documents using Microsoft Word 2013, each with more than 100 fields; some of which were in tables of various sizes. I started out doing it the way we were all taught: Insert –> Quick Parts –> Field –> MergeField. This got old awfully quick and I couldn’t envision doing this more than 100 times so I wrote a macro. Who wouldn’t? The macro only took a few minutes and a couple lines of code, see the snippet below:
Sub InsertCustomField()
    Dim sFieldName As String
    sFieldName = InputBox("Please enter field name")
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= "MERGEFIELD " & sFieldName, PreserveFormatting:=True
End Sub

I assigned the macro to the “Insert” key and went about my work. When I got to the first table I needed to insert I decided to write another macro, as follows:
Sub InsertTable_w_Header()
    Dim numRows As Integer, numCols As Integer, numNewTable As Integer
    Dim sCaption As String
    numRows = InputBox("How many rows?", "Rows", 3)
    numCols = InputBox("How many columns?", "Columns", 4)
    sCaption = InputBox("What is the 'caption' for this table?", "Caption")
    ActiveDocument.Tables.Add Range:=Selection.Range, numRows:=numRows, NumColumns:=numCols, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
    numNewTable = ActiveDocument.Tables.Count
    With ActiveDocument.Tables(numNewTable)
        If .Style "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
    Selection.MoveRight Unit:=wdCharacter, Count:=numCols, Extend:=wdExtend
    Selection.Cells.Merge
    Selection.Font.Bold = wdToggle
    Selection.TypeText Text:=sCaption
    Selection.Borders(wdBorderTop).LineStyle = wdLineStyleNone
    Selection.Borders(wdBorderLeft).LineStyle = wdLineStyleNone
    Selection.Borders(wdBorderBottom).LineStyle = wdLineStyleNone
    Selection.Borders(wdBorderRight).LineStyle = wdLineStyleNone
    Selection.Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
    Selection.Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
    With Selection.Borders(wdBorderBottom)
        .LineStyle = Options.DefaultBorderLineStyle
        .LineWidth = Options.DefaultBorderLineWidth
        .Color = Options.DefaultBorderColor
    End With
    Selection.MoveDown Unit:=wdLine, Count:=1
    Selection.MoveRight Unit:=wdCharacter, Count:=numCols, Extend:=wdExtend
    Selection.Font.Bold = wdToggle
    Selection.Shading.Texture = wdTextureNone
    Selection.Shading.ForegroundPatternColor = wdColorAutomatic
    Selection.Shading.BackgroundPatternColor = -603930625
    With ActiveDocument.Tables(numNewTable)
        .TopPadding = InchesToPoints(0.02)
        .BottomPadding = InchesToPoints(0.02)
        .LeftPadding = InchesToPoints(0.08)
        .RightPadding = InchesToPoints(0.08)
        .Spacing = 0
        .AllowPageBreaks = True
        .AllowAutoFit = False
    End With
End Sub

The last macro I needed to write for this project was for inserting a checkbox. This macro is a little more involved than the “insert field” but not as much as “insert table”. Check it out:
Sub ApplicationInsertCheckbox()
    Dim sFieldName As String
    sFieldName = InputBox("Please enter field name")
    Selection.FormFields.Add Range:=Selection.Range, Type:=wdFieldFormCheckBox
    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    With Selection.FormFields(1)
        If Len(sFieldName) >= 1 Then
            .Name = sFieldName
        End If
        .Enabled = True
        .OwnHelp = False
        .HelpText = ""
        .OwnStatus = False
        .StatusText = ""
        With .CheckBox
            .AutoSize = False
            .Size = 8
            .Default = False
        End With
    End With
    Selection.MoveRight Unit:=wdCharacter, Count:=1
End Sub

That’s it! The above code cut my development time by more than 50% and ensured consistency throughout the document. I put the code in a module that I named “mFieldAutomation” and saved my document as a TEMPLATE. I now had the basic layout for most of the documents I will have to create and the code to make it a much more efficient task. I also created another module named “mDocumentDoc” which contains a couple macros that create lists of fields and tables in a document. I will write about those macros in an upcoming post.

If you would like to know more about this project or have one you would like to discuss, please write to me at joevalencia32@gmail.com.


Filed under: Microsoft Office, Programming, VBA, Word Tagged: automate, checkbox, document automation, form field, InputBox, mail merge, Microsoft, Microsoft Word, String     sFieldName, table, vba

Viewing all articles
Browse latest Browse all 16

Trending Articles