使用 VBA 将表格定位在 Word 文档中的特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4900352/
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-11 12:37:27  来源:igfitidea点击:

Positioning a table at a specific location in a Word Document using VBA

vbams-wordword-vba

提问by Pirificio

I have written a macro to allow a user to select an office branch from a combo box, and now I want to insert the relevant address into the word document at a specific location. I have it using a table to hold the address, however when the table is created, it is created at wherever position the cursor just happens to be sitting at on the page.

我已经编写了一个宏来允许用户从组合框中选择一个办公室分支,现在我想将相关地址插入到特定位置的 word 文档中。我使用表格来保存地址,但是当创建表格时,它会在光标刚好位于页面上的任何位置创建。

I can't seem to find a way to tell the table to position exactly (x,y) where I need it to appear. Since there is nothing else in the document but text, there is nothing to reference to.

我似乎无法找到一种方法来告诉表格将 (x,y) 准确定位在我需要它出现的位置。由于文档中除了文本之外没有其他内容,因此没有任何可参考的内容。

I am also trying to stay away from using Active X controls if at all possible.

如果可能的话,我也尽量避免使用 Active X 控件。

回答by Dick Kusleika

This code will add a three column, one row table between the second and third paragraphs.

此代码将在第二段和第三段之间添加一个三列一行的表格。

Sub InsertTable()

    Dim tbl As Table
    Dim pg As Paragraph

    With ThisDocument
        'Add a new paragraph that the table will replace
        Set pg = .Paragraphs.Add(.Paragraphs(3).Range)
        'Add a table in place of the new paragraph
        Set tbl = .Tables.Add(pg.Range, 1, 3)
    End With

    tbl.Columns(1).Cells(1).Range.Text = "123 Main St"
    tbl.Columns(2).Cells(1).Range.Text = "City"
    tbl.Columns(3).Cells(1).Range.Text = "State"
    tbl.Rows.LeftIndent = 41

End Sub

回答by nobitavn94

You may use this to position table both horizontally and vertically

您可以使用它来水平和垂直放置表格

tbl.Rows.HorizontalPosition = 150 'In points
tbl.Rows.VerticalPosition = 200

Hope that helped.

希望有所帮助。

回答by Albin

I had trouble grasping the code with the with-statement from Dick Kusleika's answer, so I'd like to share my version without the with-statement, for people like me much easier to understand:

我无法通过Dick Kusleika 的回答中的 with 语句来掌握代码,所以我想分享我的版本,而不是 with 语句,因为像我这样的人更容易理解:

Sub InsertTable()

Dim tbl As Table
Dim pg As Paragraph

'Add a new paragraph that the table will replace
Set pg = ThisDocument.Paragraphs.Add(ThisDocument.Paragraphs(3).Range)
'Add a table in place of the new paragraph
Set tbl = ThisDocument.Tables.Add(pg.Range, 1, 3)

tbl.Columns(1).Cells(1).Range.Text = "123 Main St"
tbl.Columns(2).Cells(1).Range.Text = "City"
tbl.Columns(3).Cells(1).Range.Text = "State"
tbl.Rows.LeftIndent = 41

End Sub