簡體   English   中英

select 使用 vba 並復制到另一個文檔的末尾並保留格式的一個 Word 文檔中的一系列文本

[英]select a range of text from one Word doc using vba and copy to end of another document and RETAIN formatting

我有一個文檔“mydoc1”,其中包含“參加考試”和“提出問題”標題,在這些標題中選擇了要復制到另一個文檔“mydoc2”末尾的文本。 但是,該選擇具有特定的格式,當我復制並粘貼到另一個文檔中時,我想保留這些格式。 它工作正常,除了復制時不保留格式。

Sub CutSection()
'
' CutSection Macro
'
' Purpose: display the text between (but not including)
' the words "Take the Exam" and "Ask a Question" if they both appear.
Dim rng1 As Range
Dim rng2 As Range

Dim strTheText As String

Documents.Open FileName:="/Users/xxx/Desktop/mydoc1.docx"

Set rng1 = ActiveDocument.Range
If rng1.Find.Execute(FindText:="Take the Exam") Then
    Set rng2 = ActiveDocument.Range(rng1.End, 
    ActiveDocument.Range.End)
    If rng2.Find.Execute(FindText:="Ask a Question") Then
        strTheText = ActiveDocument.Range(rng1.End, rng2.Start).Text
        MsgBox strTheText
    End If
End If

Documents("/Users/xxx/Desktop/mydoc2.docx").Activate
ActiveDocument.Content.InsertAfter strTheText

End Sub

字符串不包含任何格式數據,只有文本。

您可以簡單地復制並粘貼文本:

Sub CutSection2()
   Dim doc1 As Document, doc2 As Document
   Dim rng1 As Range, rng2 As Range

   Set doc1 = Documents.Open(FileName:="/Users/xxx/Desktop/mydoc1.docx")
   Set doc2 = Documents("/Users/xxx/Desktop/mydoc2.docx")

   Set rng1 = doc1.Range
   If rng1.Find.Execute(FindText:="Take the Exam") Then
      Set rng2 = doc1.Range(rng1.End, doc1.Range.End)
      If rng2.Find.Execute(FindText:="Ask a Question") Then
         doc1.Range(rng1.End, rng2.Start).Copy
         doc2.Characters.Last.PasteAndFormat wdFormatOriginalFormatting
      End If
   End If
End Sub

或者,最好的選擇是,您可以使用FormattedText屬性來傳輸文本,而無需使用剪貼板。

Sub CutSection3()
   Dim doc1 As Document, doc2 As Document
   Dim rng1 As Range, rng2 As Range

   Set doc1 = Documents.Open(FileName:="/Users/xxx/Desktop/mydoc1.docx")
   Set doc2 = Documents("/Users/xxx/Desktop/mydoc2.docx")

   Set rng1 = doc1.Range
   If rng1.Find.Execute(FindText:="Take the Exam") Then
      Set rng2 = doc1.Range(rng1.End, ActiveDocument.Range.End)
      If rng2.Find.Execute(FindText:="Ask a Question") Then
         doc2.Characters.Last.FormattedText = doc1.Range(rng1.End, rng2.Start).FormattedText
      End If
   End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM