2015-10-05 73 views
1

此代碼允許將「myStyleTwo」的樣式「myStyleOne」更改爲全部文本。將一種風格的最後一段變爲另一種風格,ms字,VBA

Option Explicit 
Sub replaceStyleForAnotherStyle() 
Selection.Find.ClearFormatting 
Selection.Find.Style = ActiveDocument.Styles("myStyleOne") 
Selection.Find.Replacement.ClearFormatting 
Selection.Find.Replacement.Style = ActiveDocument.Styles("myStyleTwo") 
With Selection.Find 
    .Text = "" 
    .Replacement.Text = "" 
    .Forward = True 
    .Wrap = wdFindContinue 
    .Format = True 
    .MatchCase = False 
    .MatchWholeWord = False 
    .MatchWildcards = False 
    .MatchSoundsLike = False 
    .MatchAllWordForms = False 
End With 
Selection.Find.Execute Replace:=wdReplaceAll 
End Sub 

應該採取什麼碼的樣子,如果我想打開僅最後一段「myStyleOne」到「myStyleTwo」的

回答

0

要找到一個給定的風格的最後一段:

Function lastOfStyle(st As String) As Paragraph 
    For i = ActiveDocument.Paragraphs.Count To 1 Step -1 
     If ActiveDocument.Paragraphs(i).Style = st Then 
      Set lastOfStyle = ActiveDocument.Paragraphs(i) 
      Exit Function 
     End If 
    Next 
End Function 

現在你可以用這個簡單的語句改變風格:

lastOfStyle("MyStyle1").Style = "MyStyle2" 

但是,如果你想這樣做在您的宏,由於其他原因,我錯過了,那麼你應該在宏的開頭添加以下內容:

Dim p as Paragraph: Set p = lastOfStyle("Normal") 
if p Is Nothing then Exit Sub 
p.Range.Select 

然後在With Selection.Find集合中設置.Wrap = wdFindStop而不是* .Wrap = wdFindContinue *

+0

謝謝。我已經重寫了它,但是現在它找到了文本中的最後一段,而不是「myStyleOne」的最後一段... 代碼在這裏:[http://codepad.org/WqpN0AUx](http://codepad .ORG/WqpN0AUx)。 或者這是否意味着代碼必須包含一個循環來查找「myStyleOne」的最後一段?如果是這樣,那麼它應該是什麼樣子..? – ZolVas

+0

@Zolvas是的它必須是一個簡單的循環,我將它添加到我編輯的答案。但是,正如你所看到的那樣,如果只是改變這個找到的段落的風格,那麼可以用一個陳述來完成。 –

+1

謝謝! 1)在函數中:但是我認爲你應該替換「ActiveDocument.Paragraphs.Count」的「Paragraphs.Count」和「If ActiveDocument.Paragraphs(i).Style」中的「If Paragraphs(i).Style」。否則,它會解決一個錯誤; 2)在第二個代碼塊中:出於同樣的原因,「=」「MyStyle2」)也應該替換爲= =「MyStyle2」,即沒有括號。 如果你考慮以這種方式改進答案,那將是非常好的。然後,我會選擇這個答案作爲最有用的,並會顯示我的一堆代碼,這也可能曾經有用的人... – ZolVas

0

你見過這個答案嗎?它確實有幫助:answer。你可能知道的東西:在VBA中有子程序(子)和函數。函數可以在許多子程序中使用,應該分開。

太好了。你想複製並使用代碼?在這裏,只需將它全部複製到功能區上的開發人員選項卡即可:http://codepad.org/Wd5Rer4y。然後你可以運行subreplaceStyleForAnotherStyleSimple()subreplaceStyleForAnotherStyleComplicated()。他們兩人都依靠功能lastOfStyle。點擊alt + f8並明智地選擇。

太好了。但是沒有功能可以做同樣的事情嗎? 當然!它來了! replaceStyleForAnotherStyleNoFunction()

Sub replaceStyleForAnotherStyleNoFunction() 
    Dim parCountDown, i, sMyPar 
    parCountDown = ActiveDocument.Paragraphs.Count 
    For i = parCountDown To 1 Step -1 
     If ActiveDocument.Paragraphs(i).Style = "myStyleOne" Then 'change the part for: "Normal" 
      ActiveDocument.Paragraphs(i).Style = "myStyleTwo" 'change the part for: "Heading 1" 
      'sMyPar = ActiveDocument.Paragraphs(i).Range.Text 
      'MsgBox (sMyPar) 'message box with that paragraph 
      Exit Sub 
     End If 
    Next 
End Sub 

所以你在這裏看到三種方式做同樣的事情,簡單的路徑複製了這一切。敬請期待,祝你好運!

相關問題