我第一次在 stackoverflow 上寫一個問題,使用了 5 年多!希望我沒有錯過另一篇文章中的答案,并且我會達到預期提出問題的標準:
我正在嘗試根據用戶輸入動態移動 MS-word 檔案中的文本,使用標題來查找要移動的內容和移動的位置。
舉個例子,假設我的檔案是這樣組織的:
第 1 節 第 2 節 第 3 節 附件 1
“Section 1”、“Section 2”、“Section 3”和“Annex”被定義為標題 1 樣式。
在每個部分(和附件)中,您都有混合批次的文本、表格、圖片等。
假設用戶通過 VBA 被問到以下問題(通過按鈕單擊事件或檔案打開事件觸發,沒關系 - 我知道該怎么做)。根據他們的回答,我想要么
a) 什么都不做
b) 執行以下操作:
選擇整個“第 1 節”,包括標題和其中的所有文本、數字、表格等(換句話說 - 直到“第 2 節”開始)
在 Section 3 和 Annex 1 之間移動它,這樣檔案結構現在看起來像這樣: Section 2 Section 3 Section 1 Annex 1
Dim answer as Integer
answer = MsgBox("Do you like cookies?", vbQuestion vbYesNo vbDefaultButton2, "The big question")
if answer = vbYes Then
' e.g. do nothing or end sub
else
' move text as described above
我當然已經探索/閱讀了很多關于 selection.find、selection.move 和 range.move 方法的帖子。
我已經到了一個階段,我設法使用以下代碼找到并選擇我感興趣的部分;
Dim answer as Integer
answer = MsgBox("Do you like cookies?", vbQuestion vbYesNo vbDefaultButton2, "The big question")
if answer = vbYes Then
' e.g. do nothing or end sub
else
Selection.WholeStory
Selection.Collapse wdCollapseStart
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
With Selection.Find
.Text = "Section 1"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = True
End With
Selection.Find.Execute
Selection.Collapse wdCollapseStart
Dim r1 As Range
Set r1 = Selection.Range
' keep format settings, only change text
Selection.Find.Text = "Section 2"
If Selection.Find.Execute Then
Selection.Collapse wdCollapseStart
Else
Selection.WholeStory
Selection.Collapse wdCollapseEnd
End If
Dim r2 As Range
Set r2 = ActiveDocument.Range(r1.Start, Selection.Start)
r2.Select
但我很難到達終點線 - 現在根據標題將此范圍(或此選擇)移動到檔案中的另一個位置(在這種情況下,將本節插入“第 3 節”和“附件 1”之間)。
有什么建議?
uj5u.com熱心網友回復:
您在正確的路線上,但需要避免使用該Selection物件。在極少數情況下使用Selection是不可避免的,但這不是其中之一。
Word 有許多隱藏的預定義書簽,其中一個會回傳標題級別的全部范圍。這在下面的 GetHeadingBlock 函式中使用。
ARange還有一個FormattedText可以用來代替剪貼板的屬性。
Sub MoveSection()
Dim moveRange As Range, destRange As Range
Set moveRange = GetHeadingBlock("Section 1", wdStyleHeading1)
If Not moveRange Is Nothing Then
Set destRange = GetHeadingBlock("Section 3", wdStyleHeading1)
If Not destRange Is Nothing Then
destRange.Collapse wdCollapseEnd
destRange.FormattedText = moveRange.FormattedText
moveRange.Delete
End If
End If
End Sub
Public Function GetHeadingBlock(headingText As String, headingStyle As WdBuiltinStyle) As Range
Dim findRange As Range
Set findRange = ActiveDocument.Content
With findRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = headingText
.Style = headingStyle
.Replacement.Text = ""
.Forward = True
.Format = True
.Wrap = wdFindStop
If .Execute Then Set GetHeadingBlock = _
findRange.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
End With
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452339.html
