Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Word VBA中组合两个表?_Vba_Ms Word - Fatal编程技术网

如何在Word VBA中组合两个表?

如何在Word VBA中组合两个表?,vba,ms-word,Vba,Ms Word,我正在尝试向文档中添加一个新表,并将此表添加到上面的表中,以便在末尾只有一个表(换句话说,组合两个表)。 当我使用下面的代码时,这两个表连接在一起,但是宽度不同,尽管这两个表之前的宽度完全相同 Dim docSource As Document Dim docTarget As Document Set docTarget = ActiveDocument Set docSource = Documents.Open(strFileName) ' Fill docTarget with the

我正在尝试向文档中添加一个新表,并将此表添加到上面的表中,以便在末尾只有一个表(换句话说,组合两个表)。 当我使用下面的代码时,这两个表连接在一起,但是宽度不同,尽管这两个表之前的宽度完全相同

Dim docSource As Document
Dim docTarget As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFileName)
' Fill docTarget with the content of docSource
' Insert selected Table with selected Content
Dim myRange As Object
Set myRange = docTarget.Content
myRange.Collapse Direction:=wdCollapseEnd
myRange.FormattedText = docSource.Tables(1).Range.FormattedText
' Close docSource without saving
docSource.Close (0)
Set docSource = Nothing
Set docTarget = Nothing
欢迎任何意见


注意:我试图在两个表之间插入一个段落(在本例中,两个表的宽度相同),但我不知道如何通过代码删除此段落。如果我手动执行此操作,则这两个表将很好地对齐。

您可以使用最后一个表范围的“.Previous”方法查找上一段并将其删除

ActiveDocument.StoryRanges(wdMainTextStory).Tables(ActiveDocument.StoryRanges(wdMainTextStory).Tables.Count).Range.Previous(unit:=wdParagraph).Delete
多亏了“自由流”,我根据他的建议找到了解决方案

myRange.Tables(myRange.Tables.Count).Range.Previous(Unit:=wdParagraph).Select
Selection.Delete
我选择段落,然后删除所选内容,而不是直接删除。当我想到它时,它是我手工做的。奇怪的是,我不再有与表对齐的问题

我还想知道“Content”和“StoryRanges(wdMainTextStory)”之间有什么区别,但那是另一回事。

在我的代码中将“ActiveDocument”替换为“docTarget”后,它删除了段落,但两个表没有对齐,在这种情况下,每个表的宽度保持不变。我真的不明白为什么当我手动(没有VBA)而不是使用一行代码时,它工作得很好。