使用 VBA 在 MS Word 中创建表格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13366136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:24:52  来源:igfitidea点击:

creating tables in MS Word using VBA

vbams-wordword-vba

提问by Doolie1106

What are the codes to create a table in MS Word?

在 MS Word 中创建表格的代码是什么?

I've used the record function for macro to see how it is written and i have no idea how to interpret this.

我已经使用宏的记录函数来查看它是如何编写的,但我不知道如何解释它。

and can you not draw tables while recording a macro? It greys out the "draw table" function.

录制宏时不能绘制表格吗?它使“绘图表”功能变灰。

I need to make a talbe that has some merged cells within the table - it would be easier if i can draw the table and record using macro but it seems like i can't do that...

我需要制作一个表格,在表格中包含一些合并的单元格 - 如果我可以绘制表格并使用宏记录会更容易,但似乎我不能这样做......

table

桌子

I've used the draw function to draw the follow table but i can't record it.

我已经使用draw函数绘制了下表,但我无法记录它。

HELP?!

帮助?!

回答by Tim Williams

This should get you started.

这应该让你开始。

Sub Tester()


    Dim x, w, c

    ThisDocument.Tables(1).Delete

    ThisDocument.Tables.Add Range:=Selection.Range, NumRows:=7, NumColumns:=1, _
                          DefaultTableBehavior:=wdWord9TableBehavior, _
                          AutoFitBehavior:=wdAutoFitFixed

    With ThisDocument.Tables(1)

        .Rows.Height = 70
        w = .Rows(1).Cells(1).Width

        .Rows(1).Cells(1).Split 1, 7
        .Rows(1).Cells(1).Width = w / 2
        For x = 2 To 7
            .Rows(1).Cells(x).Width = (w / 2) / 6
        Next x

        .Rows(5).Height = 15
        .Rows(7).Height = 15

        .Rows(7).Cells(1).Split 1, 7

        .Rows(6).Cells(1).Split 1, 4
        .Rows(6).Cells(2).Split 2, 1

        'Once you merge cells it gets difficult to use .Rows, but
        '  you can still address individual cells. Use the loop below to
        '  find out which one you need to operate on...
        x = 1
        For Each c In .Range.Cells
            c.Range.Text = x
            x = x + 1
        Next c

        .Range.Cells(16).Split 1, 4
        'you can figure out setting the exact required widths...
    End With
End Sub

回答by SeanC

the basic command for making a table is

制作表格的基本命令是

ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=4, NumColumns:= 3

and to split/merge cells:

并拆分/合并单元格:

Selection.Cells.Split NumRows:=1, NumColumns:=2
Selection.Cells.Merge

回答by Alain

You could create the table and then save it as an autotext (select table - ALT+F3 - name of the autotext). Then when you need the table in a document, just type the name you gave it and press F3.

您可以创建表格,然后将其另存为自动文本(选择表格 - ALT+F3 - 自动文本的名称)。然后,当您需要文档中的表格时,只需键入您给它的名称并按 F3。