PDA

View Full Version : Solved: Macro to change all styles to a specific language



superpatrick
07-17-2012, 11:57 AM
I'm having some difficulty with the VBA language. What I want to do is to select all Styles in a template and set them all to Canadian English. At the same time I know there might be some errors because some Styles do not have languages at all. Here is my current code


Sub ChangeStyle()
Set tempDoc = ActiveDocument.AttachedTemplate.OpenAsDocument
Set stylish = tempDoc.Styles

For Each stylish In tempDoc
stylish.LanguageID = wdEnglishCanadian
Next

tempDoc.Close SaveChanges:=wdSaveChanges
ActiveDocument.UpdateStyles
End Sub


I'm having a rather difficult time wrapping my head around Collections and using For Each with it. If someone could help me out, that would be fantastic. I don't mind if someone gives me the answer right away, but I would also like to learn :)

macropod
07-17-2012, 03:53 PM
Try:
Sub ChangeStyle()
Dim oDoc As Document, oSty As Style
Set oDoc = ActiveDocument.AttachedTemplate.OpenAsDocument
With oDoc
For Each oSty In .Styles
oSty.LanguageID = wdEnglishCanadian
Next
.Close SaveChanges:=wdSaveChanges
End With
ActiveDocument.UpdateStyles
End Sub

gmaxey
07-17-2012, 07:29 PM
Paul,

Here at least your code needs error handling:

Sub ChangeStyle()
Dim oDoc As Document, oSty As Style
Set oDoc = ActiveDocument.AttachedTemplate.OpenAsDocument
With oDoc
For Each oSty In .Styles
On Error GoTo Err_Handler
oSty.LanguageID = wdEnglishUS
Err_ReEntry:
Next
.Close SaveChanges:=wdSaveChanges
End With
ActiveDocument.UpdateStyles
Exit Sub
Err_Handler:
Resume Err_ReEntry
End Sub

macropod
07-17-2012, 07:33 PM
Oops. I'd probably handle errors a little differently though:
Sub ChangeStyle()
Dim oDoc As Document, oSty As Style
Set oDoc = ActiveDocument.AttachedTemplate.OpenAsDocument
With oDoc
For Each oSty In .Styles
On Error Resume Next
oSty.LanguageID = wdEnglishCanadian
On Error GoTo 0
Next
.Close SaveChanges:=wdSaveChanges
End With
ActiveDocument.UpdateStyles
End Sub

gmaxey
07-17-2012, 07:37 PM
Paul,

I did it the way I did so I could step through and see which actually passed. In practice I would use the Resume Next as well.

macropod
07-17-2012, 07:42 PM
Fair enough.

superpatrick
07-18-2012, 05:51 AM
This is an excellent solution. Thank you so much for the help! I shall mark the thread as solved.