Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Renaming styles in a word document 1

Status
Not open for further replies.

amillia

Programmer
Nov 14, 2001
124
US
What would be the best way to rename styles in a word document? Could I use a search and replace procedure?
 
Hi,

You certainly could use Find & Replace with styles. If you do this manually with the macro recorder switched on, Word will generate some basic code to get you started.

You'll find 'Style' as one of the available options under Edit|Find|More|Format.

Cheers
 
Thankyou, I just realized that I have a much bigger problem. Most of the document are not formatted with styles at all. They use manual formatting so now I am thinking I will use an if then statement. Does anyone know what the main formatting attributes are that make up a style?
 
I guess the real question is "can I programmatically apply a style to text that has never had a style applied before?
 
This is what I have written so far but it doesn't do anything. It doesn't give an error but it doesn't make the text have a style either.

Sub AddedStyle()
If ActiveDocument.Content.Font.Name = "Arial" And ActiveDocument.Content.Font.Size = "12" Then
Set ActiveDocument.Content.Style = "para"
End If

End Sub
 
Hi,

Basically, what you'd need to do is to test each para and see what style it's got (because Word sometimes applies styles of it's own accord, based on the hard formatting), and whether the formatting matches the style. If not, you can modify the style, or define a new style. The former gets tricky if you've already accepted a paragraph in that style or modified the style, because changing it a second time will aplly the changes to the all paragraphs using that style.

Personally, I'd be creating/importing some suitable styles and manually applying them to all paragraphs of a given format.

Cheers
 
LaurenNichole said:
I guess the real question is "can I programmatically apply a style to text that has never had a style applied before?"

All text in any Word document has a style. If you haven't applied it, Word has.

I don't think you will be able to write an automatic process that will save you time and I would just buckle down and do it manually - hotkey combinations for applying styles can help speed up your work and the human eye is pretty good.

One day, when I have time, I would like to play with this kind of thing but it isn't easy - you really have to look at every character individually to determine all the styling that has been applied.

Enjoy,
Tony

--------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.
Excel VBA Training and more Help at VBAExpress[
 
1. ActiveDocument.Content.Font.Name = "Arial" is code that applies to the entire document, ie. "Content"...not paragraphs.

2. Can you apply a style programatically? Yes. And it does not make any difference whether it has had a style applied previously, or not. Styles can be applied programtically to a Selection, to a Range, or to any other object that accepts a style.

To make the Selection a style
Code:
Sub TestSelection()
Selection.Style = "TestStyle"
End Sub

Note however, if the Selection is NOT the whole paragraph, only the actual selected text of the paragraph becomes that style - even if the style is a paragraph style. If required, you could add code to make sure the Selection includes the entire paragraph.

To make a range a style, use something like:
Code:
Sub TestRange()
Dim oRange As Word.Range
Set oRange = ActiveDocument.Paragraphs(7).Range
oRange.Style = "teststyle"
Set oRange = Nothing
End Sub

The above makes a range of the seventh paragraph, then applies the style to it.

Note: it uses an explicit Range object, but you could also use the Range property of any other object that has a Range property.

You can also use, as stated, any other object that has a style property, like the Paragraph object. The following explicitly makes the fourth paragraph a specific style.

Code:
Sub TestParagraph()
Dim oPara As Word.Paragraph
Set oPara = ActiveDocument.Paragraphs(4)
oPara.Style = "TestStyle"
Set oPara = Nothing
End Sub

You can also build an array of existing Styles, and then use that array to apply the styles. Thje following uses an array of three styles, and applies then - in order - to the first three paragraphs in the document.

Code:
Sub TestStyleArray()
Dim myStyles(2) As String
Dim var
myStyles(0) = "TestStyle"
myStyles(1) = "TestStyle2"
myStyles(2) = "TestStyle3"
For var = 0 To 2
    ActiveDocument.Paragraphs(var + 1).Style = myStyles(var)
Next
End Sub

The above could be messed around with in a number of ways. I am just tossing these off to help give you an idea of what you can do.

Gerry
 
Thank you Gerry for your help. I have been trying some thing between posts. Could you look at the code I have written and give me some input. I think I am very close. I want to be able to go through the whole document and according to what is already there I want to assign a name to the style.

Sub Macro19()
'
' Macro1 Macro
' Macro recorded 10/4/2005 by
'
Dim intLONGy As Integer
Dim intSTARTy As Integer
Dim intENDy As Integer
Dim intFOUNDy As Integer

intSTARTy = 1
intFOUNDy = 1
intLONGy = Len(ThisDocument.Range.Text)


Do Until intSTARTy > intLONGy

intFOUNDy = InStr(intSTARTy, ThisDocument.Range.Text, Chr(13), vbBinaryCompare)

If intFOUNDy > 0 Then
intENDy = intFOUNDy
Else

End If

Selection.Start = intSTARTy - 1
Selection.End = intENDy

If Selection.Font.Name = "Arial" And Selection.Font.Size = 10 Then
Selection.Style = "para4"
Else
MsgBox "not arial"
End If
intSTARTy = intENDy + 1
Loop


End Sub



I have about 25 different styles that I need to apply to the documents, so I need a macro that I can run over and over or possibly put different possiblities in the same procedure.
 
I want to be able to go through the whole document and according to what is already there I want to assign a name to the style.

This is inconsistent with what your code is doing. According to the above statement:

Paragraph 1 - font = Times Roman; font size = 12; Bold = True

Paragraph 2 - font = Times Roman; font size = 10; Bold = False

Paragraph 3 - font = Arial; font size = 11; Bold = False

OK, all three are different. The quote above states that you want to CREATE (name) a style based on the existing format.

Your code, however, is applying a style, based on what is the existing font. You are checking to see if it Arial, or not. It is not naming a style based on existing format.

Which are you trying to do?


Gerry
 
I meant according to the existing format I want to apply a style.
 
I suppose what I will actually have to do is create the styles I will need and then I will have to go through and apply them. Is this correct?
 
BINGO!

If you need help with this, ask. I have a ranting reputation to keep up regarding styles.....

Gerry
 
For what PH? My BINGO!, or my acknowledgement that I rant.

Gerry
 
Do you guys see what is wrong with my selection loop because it is only going to like the first character?
 
OK,

1. If you are doing any count at the character level in Word do NOT use integers, use Long. You would be quite surprised at how quickly an integer data type runs out of gas in a Word document. Besides which, Word itself uses Long for any character counting.

2. Your code is a little funny. You have:
intFOUNDy = 1

and then

intFOUNDy = InStr(intSTARTy, ThisDocument.Range.Text, Chr(13), vbBinaryCompare)

Why make it = 1 in the first place?

3. Do not use the Selectiion object unless you need to. There absolutely no point in making a Selection here.

From what I gather from your code, you are attempting to check each paragraph - by using the Chr(13) - then selecting from it.

Bleeech. Here is something that may help you get on your way a bit better
Code:
Sub eachParagraph()
Dim oPara As Word.Paragraph
For Each oPara In ActiveDocument.Range.Paragraphs()
    If oPara.Style = "para4" Then
        MsgBox "Yup para4"
    End If
    If oPara.Range.Font.Bold = True Then
        MsgBox "Yeah....this paragraph is bolded...so what?"
    End If
Next
End Sub

You can, of course, ignore my flippant lines. If what you are doing is checking each paragraph, then use a paragraph object. 'Tis much easier. The first IF demonstrates checking the style of each paragraph; the second checks if bold is on, or not.

Hope this helps.

Oh, and your Selection code? Try stepping through the code and putting your mouse over the variables - or do a debug.print. You will be surprised by the values.

Oh and you have If intFOUNDy > 0 Then

intFOUNDy is ALWAYS going to be greater than 0....after all you already set it yourself = 1.

Gerry
 
Thank you this will work great. When I test for a style and I have multiple if's like below is there a better way to write this?

If oPara.Range.Font.Name = "Arial" And oPara.Range.Font.Bold = False And oPara.Range.Font.Italic = False And oPara.Range.Font.Underline = wdUnderlineNone And oPara.Range.Font.UnderlineColor = wdColorAutomatic And oPara.Range.Font.StrikeThrough = False And oPara.Range.Font.DoubleStrikeThrough = False And oPara.Range.Font.Outline = False And oPara.Range.Font.Emboss = False And oPara.Range.Font.Shadow = False And oPara.Range.Font.Hidden = False And oPara.Range.Font.SmallCaps = False And oPara.Range.Font.AllCaps = False Then
oPara.Range.Style = "Style1
 
1. First off, it is better to post code in a code window, rather than in the post as text. Also, it is a good habit to use the underscore character to break extended lines of code. Makes it MUCH easier to read. So, let's see what you have....
Code:
If oPara.Range.Font.Name = "Arial" And _
  oPara.Range.Font.Bold = False And _
  oPara.Range.Font.Italic = False And _
  oPara.Range.Font.Underline = wdUnderlineNone And _
  oPara.Range.Font.UnderlineColor = wdColorAutomatic And _
  oPara.Range.Font.StrikeThrough = False And _
  oPara.Range.Font.DoubleStrikeThrough = False And _
  oPara.Range.Font.Outline = False And _
  oPara.Range.Font.Emboss = False And _
  oPara.Range.Font.Shadow = False And _
  oPara.Range.Font.Hidden = False And _
  oPara.Range.Font.SmallCaps = False And _
  oPara.Range.Font.AllCaps = False Then
        oPara.Range.Style = "Style1"
'  blah blah

2. You understand, I hope, that oPara will only be made Style1 if ALL of those conditions are true. If even one of them is not true, then the style is not set to Style1.

3. You are going about this incorrectly. Did you actually make a style named Style1? You must have for this to work at all, otherwise oPara.Range.Stuyle = "Style1" will fail. If you DID make a Style1, go back and delete and start again. Style1 is the defauilt name that Word gives a new style. It is poor programming (other than for demonstation purposes, like here in this forum) to accept default names. It is general best practice to give things names that make sense, are readable, and work from a consistent convention.

What does "Style1" say? Diddley. "BodyTextBold" says something. BodyText_Indent1.5 says something. "FooterFilename" says something. Etc etc.

4. Try to follow through logically with what you are actually, REALLY, trying to do. Then tell me what that is. Because you have not stated exactly what you are trying to do. Your code makes all sorts of conditions for what IS EXISTING in format for a paragraph. Then if all of those conditions are met, make the paragraph a given style. In this case......sigh....Style1. However, is that what you are really trying to do?

Please state EXACTLY, precisely, what you want to accomplish. You have to work from there.

OK everyone...take a deeeeep breath......

A properly designed document template uses styles. Styles are ALWAYS based on a BaseStyle. A newly created style has the default Name as "Style1", and the default BaseStyle is Normal. As it is not possible to delete normal style - at least as far as I know - you can ignore it, except for the first style you create. Make a style (based on normal), and forever more use THAT one for your basestyle. However, of course it is possible, and very sane, to alter normal style (ONCE!!) to be whatever you want.

Anyway, I can feel myself wandering - tired - the fact of the matter is, is....gee I keep thinking about Bill Clinton, just too many is-es, what the heck is the plural of "is": Hey wake up, this is important.

Every single paragraph mark, every one - even those ones used to make that "extra' space between paragraph - contains references to ALL possible condition of a paragraph.

Code:
    With ActiveDocument.Styles("BrandNewStyle").Font
        .Name = "Charlesworth"
        .Size = 9
        .Bold = False
        .Italic = True
        .Underline = wdUnderlineNone
        .UnderlineColor = wdColorAutomatic
        .StrikeThrough = False
        .DoubleStrikeThrough = False
        .Outline = False
        .Emboss = False
        .Shadow = False
        .Hidden = False
        .SmallCaps = False
        .AllCaps = False
        .Color = wdColorAutomatic
        .Engrave = False
        .Superscript = False
        .Subscript = False
        .Scaling = 100
        .Kerning = 0
        .Animation = wdAnimationNone
    End With
    With ActiveDocument.Styles("BrandNewStyle").ParagraphFormat
        .LeftIndent = InchesToPoints(0)
        .RightIndent = InchesToPoints(0)
        .SpaceBefore = 0
        .SpaceBeforeAuto = False
        .SpaceAfter = 0
        .SpaceAfterAuto = False
        .LineSpacingRule = wdLineSpaceSingle
        .Alignment = wdAlignParagraphLeft
        .WidowControl = True
        .KeepWithNext = False
        .KeepTogether = False
        .PageBreakBefore = False
        .NoLineNumber = False
        .Hyphenation = True
        .FirstLineIndent = InchesToPoints(0)
        .OutlineLevel = wdOutlineLevelBodyText
        .CharacterUnitLeftIndent = 0
        .CharacterUnitRightIndent = 0
        .CharacterUnitFirstLineIndent = 0
        .LineUnitBefore = 0
        .LineUnitAfter = 0
    End With
    ActiveDocument.Styles("BrandNewStyle").NoSpaceBetweenParagraphsOfSameStyle _
         = False
    ActiveDocument.Styles("BrandNewStyle").ParagraphFormat.TabStops.ClearAll
    With ActiveDocument.Styles("BrandNewStyle").ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorAutomatic
            .BackgroundPatternColor = wdColorAutomatic
        End With
        .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
        .Borders(wdBorderRight).LineStyle = wdLineStyleNone
        .Borders(wdBorderTop).LineStyle = wdLineStyleNone
        .Borders(wdBorderBottom).LineStyle = wdLineStyleNone
        With .Borders
            .DistanceFromTop = 1
            .DistanceFromLeft = 4
            .DistanceFromBottom = 1
            .DistanceFromRight = 4
            .Shadow = False
        End With
    End With
    ActiveDocument.Styles("BrandNewStyle").LanguageID = wdEnglishUS
    ActiveDocument.Styles("BrandNewStyle").NoProofing = False
    ActiveDocument.Styles("BrandNewStyle").Frame.Delete

Sorta goes on don't it? Yup, sure does.

I am going to leave this for now, and actually post a question, as I have been trying for an hour to do something, and I am feeling very stupid.

Anyway, this is just barely sratching styles. However, here again, may be a handy little code snippet.
Code:
Sub CreateStyleCurrentParagraph()
Dim trStyleName As String
strStyleName = InputBox("Name of new style?")
If Selection.Information <> wdSelectionIP Then
  Selection.Collapse Direction:=wdCollapseStart
  With ActiveDocument
     .Styles.Add Name:=strStyleName, _
        Type:= wdStyleTypeParagraph
     .Styles(strStyleName) _
        .AutomaticallyUpdate = False
  End With
Else
  With ActiveDocument
     .Styles.Add Name:=strStyleName, _
        Type:= wdStyleTypeParagraph
     .Styles(strStyleName) _
        .AutomaticallyUpdate = False
  End With
End If

This create a new style for WHATEVER is the format of the paragraph the Selection is in.

Unfortunately you can not create a new style based one a Range. It has to be the Selection object.

Here is another snippet that I am trying to hint a direction you may work on. It is possible to get a description of a style. The important thing is that it only describes the DIFFERENCES between the style and its BaseStyle.

ActiveDocument.Styles("blahblblbln").Decription could return something like:

myBase + Font:EraserDust, 16pts, Underline

This is a string, and therefore open to the full range of string manipulation. There is complicated, but do-able to kludge together something that can actually compare styles. There is no built-in comparison function - that I know of. However, you CAN use the above to do it.

I need to lie down.....

Again, what exactly are you trying do????

Gerry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top