vba 从 Word 中的表格复制文本并保留格式

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

Copy Text from Table in Word and Retaing Formatting

vbams-wordword-vba

提问by user1173805

I have a problem copying a cell from a table to another cell. I'm talking about two word documents here. I can copy the text but the bullets are gone and some of the formatting.

我在将单元格从表格复制到另一个单元格时遇到问题。我在这里谈论的是两个word文档。我可以复制文本,但项目符号和一些格式都不见了。

I tried .Formattedtextbut still can't do it.

我试过了,.Formattedtext但还是做不到。

Dim test As Word.Cell

'An error occurs something like "Object variable or With block variable not set"
test.Range.FormattedText = CTPDoc.Tables(2).Rows(testCount).Cells(3).Range.FormattedText

回答by Siddharth Rout

Here is an example.

这是一个例子。

Let's say we have two tables in a word document. See screenshot below

假设我们在一个 word 文档中有两个表格。看下面的截图

enter image description here

在此处输入图片说明

Let's say we want to paste the data from Cell 1of Table 1to Cell 1of Table 2then try this

假设我们想粘贴数据从Cell 1ofTable 1Cell 1ofTable 2然后试试这个

Sub Sample()
    Dim tbl1 As Table, tbl2 As Table

    Set tbl1 = ActiveDocument.Tables(1)
    Set tbl2 = ActiveDocument.Tables(2)

    tbl1.Cell(1, 1).Range.Copy
    tbl2.Cell(1, 1).Range.PasteAndFormat (wdFormatOriginalFormatting)
End Sub

This is what the macro does

这就是宏的作用

enter image description here

在此处输入图片说明

Hope this helps :)

希望这可以帮助 :)

回答by user1173805

@Siddharth Rout You answer was really helpful. It's not the exact answer to my problem but at least I learned about PasteandFormatand its different types such as wdFormatOriginalFormatting. maybe someday I can use that.

@Siddharth Rout 你的回答真的很有帮助。这不是我问题的确切答案,但至少我了解了PasteandFormat它的不同类型,例如wdFormatOriginalFormatting. 也许有一天我可以使用它。

Now here goes what solved my problem. Using the logic given by Siddharth, I used the simple tbl2.Cell(1, 1).Range.Pasteinstead of PasteandFormat. Actually PasteandFormatworked but there was a problem which happens in only selected source file/table. I think there's some formatting that exist in the source table that when pasted in another cell, it'll look messed up. I'm not sure about what exactly what's that but .Pastedefinitely solved it for me. I hoped I can help others too :)

现在解决了我的问题。使用 Siddharth 给出的逻辑,我使用了 simpletbl2.Cell(1, 1).Range.Paste而不是PasteandFormat. 实际PasteandFormat有效,但仅在选定的源文件/表中发生了问题。我认为源表中存在一些格式,当粘贴到另一个单元格中时,它看起来会一团糟。我不确定那到底是什么,但.Paste绝对为我解决了这个问题。我希望我也能帮助别人:)