如何在合并的Word表中添加行? [英] How to add rows to a merged Word table?

查看:213
本文介绍了如何在合并的Word表中添加行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是表格的样子。

代码

Sub WordTableTester()
Dim CurrentTable As table
Dim wdDoc As Document
Dim Rw As Long, col As Long
Dim wdFileName

wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , "Please choose a file containing requirements to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)

Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    Set CurrentTable = wdDoc.Tables(1)
    Rw = 9: col = CurrentTable.Columns.Count
    wdDoc.Range(CurrentTable.Cell(Rw, 1).Range.start, _
    CurrentTable.Cell(Rw, col).Range.start).Select
    wdDoc.Application.Selection.InsertRowsBelow
End With


End Sub

当我运行这个,我得到一个错误消息:运行时错误'5941':收集的请求的成员不存在。

When I run this, I get the an error message: Run-Time error '5941': The requested member of the collection does not exist.

注意:我正在运行一个VBA Excel宏,并在Word文档中的表中导入/添加行

Note: I'm running a VBA Excel Macro and importing/adding rows to a table in a Word Doc

推荐答案

使用MS Word表格中的合并行有点棘手。

Working with merged rows in MS Word Table is slightly tricky.

这是你想要的吗?

Sub Sample()
    Dim CurrentTable As Table
    Dim wdDoc As Document
    Dim Rw As Long, col As Long

    Set wdDoc = ActiveDocument '<~~ Created this for testing
    Set CurrentTable = wdDoc.Tables(1)

    Rw = 9: col = CurrentTable.Columns.Count

    wdDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
    CurrentTable.Cell(Rw, col).Range.Start).Select

    wdDoc.Application.Selection.InsertRowsBelow
End Sub

ScreenShot

修改

您的表的格式都被搞砸了。表创建了几行,然后单元格合并/拆分以创建新行,因此您收到错误。此外,既然您正在自动化excel中的单词,我会推荐以下方式。

You table's format is all screwed up. Table was created with few rows and then the cells were merged/split to create new rows and hence you were getting the error. Also since you are automating word from excel, I would recommend the following way.

尝试这个

Sub WordTableTester()
    Dim oWordApp As Object, oWordDoc As Object, CurrentTable As Object
    Dim flName As Variant
    Dim Rw As Long, col As Long

    flName = Application.GetOpenFilename("Word files (*.docx),*.docx", _
    , "Please choose a file containing requirements to be imported")

    If flName = False Then Exit Sub

    Set oWordApp = CreateObject("Word.Application")
    oWordApp.Visible = True

    Set oWordDoc = oWordApp.Documents.Open(flName)
    Set CurrentTable = oWordDoc.Tables(1)

    Rw = 7: col = CurrentTable.Columns.Count

    oWordDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
    CurrentTable.Cell(Rw, col).Range.Start).Select

    oWordDoc.Application.Selection.InsertRowsBelow
End Sub

这篇关于如何在合并的Word表中添加行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆