从Word文档复制VBA页面范围,并粘贴匹配格式的值

时间:2019-04-23 13:29:32

标签: excel vba ms-word

我有一个代码可以复制文档的页面范围,创建新的工作表并将数据粘贴到那里。但是,它与要复制的单词doc的格式不匹配。请参见下面的代码。 我尝试将selection.copy更改为selection.copyFormat,但它只是复制实际的VBA代码,并将其粘贴到word文档中。 子selectpages()   Dim rgePages作为范围   ThisDocument.Activate   Selection.GoTo什么:= wdGoToPage,其中:= wdGoToAbsolute,计数:= 196   设置rgePages = Selection.Range   Selection.GoTo什么:= wdGoToPage,哪个:= wdGoToAbsolute,计数:= 207   rgePages.End = Selection.Bookmarks(“ \ Page”)。Range.End   rgePages.Select   选择复制   设置objNewDoc = Documents.Add   Selection.PasteAndFormat(wdFormatPlainText)   objNewDoc.SaveAs FileName:=“ C:\ Users \ GP8535 \ Desktop \ Word Doc”&“ \”&“ SB 59_test”&“ .docx”   objNewDoc.Close 结束子

1 个答案:

答案 0 :(得分:1)

无需激活或选择任何内容。试试:

Sub CopyContent()
  Dim Rng As Range, RngTmp As Range, wdDoc As Document
  With ThisDocument
    Set Rng = .Range.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=196)
    Set RngTmp = .Range.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=207)
    Set RngTmp = RngTmp.GoTo(What:=wdGoToBookmark, Name:="\Page")
    Rng.End = RngTmp.End: Set RngTmp = Nothing
  End With
  Set wdDoc = Documents.Add
  With wdDoc
    Rng.Copy
    .Range.Characters.Last.PasteAndFormat Type:=wdFormatOriginalFormatting
    .SaveAs FileName:="C:\Users\GP8535\Desktop\Word Doc\SB 59_test.docx"
    .Close
  End With
  Set Rng = Nothing
End Sub