How Create a Specified Number of Multiple Tables in Word using VBA

By following VBA Code will allows you to create multiple tables in Microsoft Word by specifying the number of tables, rows, and columns. The user is prompted to enter the number of tables you want to create the number of rows and columns for each table. The code then automatically inserts the specified number of tables, with the given number of rows and columns, and applies a default table style (“Table Grid”) to each one. After each table is inserted, the cursor moves down to ensure that the next table is placed on a new line. This makes it easy to quickly and easily generate multiple tables in a Word document with consistent formatting.

Follow these Steps to Create Multiple Tables using VBA

  • Open VBA Editor (By pressing ALT+F11)
  • Create New Module, past the following code into the module
Create Multiple tables using VBA Code
Sub InsertMultipleTables()
    Dim rows As Integer
    Dim cols As Integer
    Dim numTables As Integer
    Dim rowsInput As String
    Dim colsInput As String
    Dim numTablesInput As String
    Dim i As Integer
    Dim currentRange As Range
    numTablesInput = InputBox("Enter the number of tables you want to create", "Number of Tables")
    rowsInput = InputBox("Enter The Number of Rows you Want", "Rows")
    colsInput = InputBox("Enter The Number of Columns you Want", "Columns")
    If numTablesInput = "" Or rowsInput = "" Or colsInput = "" Then
        MsgBox "Please enter the number of tables, rows, and columns."
    Else
        On Error GoTo InvalidInput
        numTables = CInt(numTablesInput)
        rows = CInt(rowsInput)
        cols = CInt(colsInput)
        Set currentRange = Selection.Range  
        For i = 1 To numTables
            ' Insert the table
            Dim table As table
            Set table = ActiveDocument.Tables.Add(Range:=currentRange, NumRows:=rows, NumColumns:=cols)
            table.Style = "Table Grid"
            Set currentRange = table.Range
            currentRange.Collapse Direction:=wdCollapseEnd
            currentRange.InsertAfter vbCrLf 
            currentRange.Collapse Direction:=wdCollapseEnd
        Next i
        Exit Sub
InvalidInput:
        MsgBox "Please enter valid numeric values for the number of tables, rows, and columns."
    End If
End Sub

After Pasting the Code, Press CTRL+S (to save the VBA Code), Press F5 (to RUN VBA Code) and close VBA Editor.

If you don’t know how to use and RUN VBA Code Visit the following link.

How to Use and Run VBA Code in Word, Excel, Access and PowerPoint

I hope this tutorial will help you to learn how to create specified no of multiple tables in Word using VBA Code.

Similar Posts