How to Create Tables in Microsoft Word using VBA

If you’re interested in using VBA (Visual Basic for Applications) to create tables in Microsoft Word, this tutorial is for you. You’ll learn how to create tables by specifying the number of rows and columns you want. Additionally, the tutorial will guide you on how to apply basic formatting and styling to the tables. By the end of the tutorial, you will be able to write and run VBA code that automatically creates tables in Word.

create tables in Word using VBA Code

Open VBA Editor: by Pressing ALT + F11 shortcut key from you keyboard

Insert a new module: in VBA Editor click on insert, then select module and past the following VBA Code into the module.

Sub InsertTable()
    Dim rows As Integer
    Dim cols As Integer
    Dim rowsInput As String
    Dim colsInput As String
    rowsInput = InputBox("Enter The Number of Rows you Want", "Rows")
    colsInput = InputBox("Enter the Number of Columns that you Want", "Columns")
    If rowsInput = "" Or colsInput = "" Then
        MsgBox "Enter Number of rows or columns"
    Else
        On Error GoTo InvalidInput
        rows = CInt(rowsInput)
        cols = CInt(colsInput)
        Dim table As table
        Set table = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=rows, NumColumns:=cols)
        table.Style = "Table Grid"
        Exit Sub
InvalidInput:
        MsgBox "Please enter valid numeric values for rows and columns."
    End If
End Sub
VBA Code to Create Tables in Word

After pasting the above-mentioned code into the module press CTRL+S (to Save your VBA Code), Press F5 (to directly run your code from VBA Editor) and close VBA Editor.

To use your VBA code to create tables, simply press the ALT + F8 keyboard shortcut. This will open the Macros dialog box, where you will see a list of all your created macros. From there select the macro you want to run and click the Run button.

if you want to assign keyboard shortcut to your VBA Macros visit the following link.

How to Assign keyboard shortcut to VBA Coded Macros

I hope this tutorial will help to learn how to create tables in Microsoft Word using VBA Code. If you have any question, suggestion or feedback feel free to contact us using detail provided on our contact us page.

Thank you for your feedback & support.

Similar Posts