2017-08-29 60 views
0

之後添加空格我有這個小宏,其目的是刪除所有空段(^ p),然後選擇所有段落並在之前和之後添加空格(每個6個點) 。Word VBA宏清理空段並在

這是到目前爲止的代碼

Sub format() 

ActiveDocument.Range.Select 

' Selection.Find.ClearFormatting 
Selection.Find.Replacement.ClearFormatting 
With Selection.Find 
.text = "^p^p" 
.Replacement.text = "" 
.Forward = True 
.Wrap = wdFindContinue 
.Format = False 
.MatchCase = False 
.MatchWholeWord = False 
.MatchByte = False 
.MatchAllWordForms = False 
.MatchSoundsLike = False 
.MatchWildcards = False 
.MatchFuzzy = False 
End With 
Selection.Find.Execute Replace:=wdReplaceAll 


iParCount = ActiveDocument.Paragraphs.Count 
For J = 1 To iParCount 
    ActiveDocument.Paragraphs(J).SpaceAfter = 6 
    ActiveDocument.Paragraphs(J).SpaceBefore = 6 
Next J 
End Sub 

然而,當我運行它,一切都變得一個段落。 Supose我有一個(^ P是空的段落)

paragraph 1 
^p 
paragraph 2 
^p 
paragraph 3 

我總是

paragraph 1 paragraph 2 paragraph 3 

我在做什麼錯?謝謝!

+0

您「之前」的段落示例不正確。再看看你的段落。然後想想你用什麼取代了什麼 – jsotola

回答

0

您需要使用循環完成此操作,並從文檔末尾開始,以便從計數中刪除已刪除的段落。

Sub FormatParagraphs() 

    Dim Para As Paragraph 
    Dim i As Long 

    Application.ScreenUpdating = False 
    With ActiveDocument 
     For i = .Paragraphs.Count To 1 Step -1 
      Set Para = .Paragraphs(i) 
      With Para 
       If .Range.End - .Range.Start = 1 Then 
        .Range.Delete 
       Else 
        .SpaceBefore = 6 
        .SpaceAfter = 6 
       End If 
      End With 
     Next i 
    End With 
    Application.ScreenUpdating = True 
End Sub