此代码允许为“myStyleTwo”更改带有“myStyleOne”样式的所有文本。
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 :(得分: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
然后在.Wrap = wdFindStop
块中设置With Selection.Find
而不是* .Wrap = wdFindContinue *
答案 1 :(得分:-1)
你看到过这个答案吗?它确实有帮助: answer 。你可能知道的事情:在VBA中有子程序(子)和函数。函数可以在许多子程序中使用,应该单独使用。
大。您想复制并使用该代码?在这里,您只需将其全部复制到功能区上的开发人员标签: http://codepad.org/Wd5Rer4y 。然后,您可以运行 sub replaceStyleForAnotherStyleSimple()
或 sub replaceStyleForAnotherStyleComplicated()
。它们都依赖于功能 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
所以你在这里看到了三种方法来做同样的事情和简单的方法来复制所有这些。敬请关注,祝你好运!