将一种风格的最后一段变为另一种风格,ms字,VBA

问题描述:

此代码允许将“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”的

要找到一个给定的风格的最后一段:

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

你见过这个答案吗?它确实有帮助: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 

所以你在这里看到三种方式做同样的事情,简单的路径复制了这一切。敬请期待,祝你好运!