gpt4 book ai didi

vba - 如何向合并的Word表格添加行?

转载 作者:行者123 更新时间:2023-12-03 02:29:59 27 4
gpt4 key购买 nike

这就是表格的样子。

enter image description here

代码:

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”:请求的集合成员不存在。

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

最佳答案

在 MS Word 表中处理合并行有点棘手。

这是你想要的吗?

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

屏幕截图 enter image description here

编辑

你的表格格式全部搞砸了。创建的表只有几行,然后合并/拆分单元格以创建新行,因此您收到错误。另外,由于您正在自动化 Excel 中的 Word,因此我建议采用以下方法。

试试这个

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

关于vba - 如何向合并的Word表格添加行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com