• Macro to Delete CharChar styles (Word 2002)

    Home » Forums » AskWoody support » Productivity software by function » MS Word and word processing help » Macro to Delete CharChar styles (Word 2002)

    Author
    Topic
    #402936

    All,

    The problem of unwanted “char char” styles propagating in Word 2002 documents (due to applying a paragraph style to a partially-selected paragraph) has been discussed here before, but based on a quick search, I didn’t see a good fix posted (apologies if one was, and I’ve just missed it).
    (The presence of these unwanted ‘char’ styles can be detected either by looking at the Styles tab in the Organizer, or by holding down the Shift key before looking in the Styles dropdown in the Formatting toolbar.)

    Andrew Lockton posted a related macro here, but that only gets to the char char style issue as a side effect (if I’m reading it right).

    Anyway, the following seems to work – this is expanded upon a macro posted (somewhere, cannot find source) by Cindy Meister, for deleting a single char char style. From there, it’s a small step to expand it out to delete all of the char char styles in a document:

    Public Sub RemoveAllCharCharStyles()
    
       Dim objDocStyles As Styles
       Dim objTempStyle As Style
       Dim StylesCt As Long
       Dim strStyleName As String
       Dim n As Long
       
       Set objDocStyles = ActiveDocument.Styles
       StylesCt = objDocStyles.Count
          
       For n = StylesCt To 1 Step -1
          strStyleName = objDocStyles(n).NameLocal
          If fStyleNameEndsInChar(strStyleName) Then
             Set objTempStyle = objDocStyles.Add(Name:="zTempStyle")
             On Error Resume Next
             objDocStyles(strStyleName).LinkStyle = objTempStyle
             objTempStyle.Delete
             Set objTempStyle = Nothing
          End If
       Next 'n
       
       Set objDocStyles = Nothing
    
    End Sub
    
    Private Function fStyleNameEndsInChar(StyleName As String) As Boolean
    
       If LCase$(Right$(StyleName, 4)) = "char" Then fStyleNameEndsInChar = True
    
    End Function
    

    Gary

    PS: Hi to my Lounge friends; I miss this place, keeping hoping I’ll be able work a bit less and play here more!

    Viewing 5 reply threads
    Author
    Replies
    • #806194

      Hi Gary

      We’ve missed your smiling face around here. Yes, you read my macro right – it gets rid of all style aliases rather than actually targeting the char char styles specifically.

    • #806195

      Hi Gary

      We’ve missed your smiling face around here. Yes, you read my macro right – it gets rid of all style aliases rather than actually targeting the char char styles specifically.

    • #807279

      Gary

      I’m trying to understand how this code works and wondering if you really need to create a style to link to just so you can delete that style. Can’t we just link to ‘Normal’ or ‘Default Paragraph Font’ instead? I think changing the if statement to InStr might also yield more successful hits.

      I modified your code slightly to see what is happening during the run and am still puzzled on what is happening

      Public Sub RemoveAllCharCharStyles()
         Dim objDocStyles As Styles
         Dim objTempStyle As Style
         Dim StylesCt As Long
         Dim strStyleName As String
         Dim n As Long
         
         Set objDocStyles = ActiveDocument.Styles
         StylesCt = objDocStyles.count
         Debug.Print "Total style count: " & StylesCt
         On Error Resume Next
            
         For n = StylesCt To 1 Step -1
            strStyleName = objDocStyles(n).NameLocal
            If LCase$(Right$(strStyleName, 4)) = "char" Then
               Debug.Print "Before: " & strStyleName & "::" & objDocStyles(n).LinkStyle
               Set objTempStyle = objDocStyles.Add(Name:="zTempStyle")
               objDocStyles(strStyleName).LinkStyle = objTempStyle
               Debug.Print "During: " & strStyleName & "::" & objDocStyles(n).LinkStyle
               objTempStyle.Delete
               Set objTempStyle = Nothing
               Debug.Print "After: " & strStyleName & "::" & objDocStyles(n).LinkStyle
            End If
         Next 'n
         Set objDocStyles = Nothing
      End Sub

      Now when I run this code twice to compare the results, I discovered that despite the code not physically deleting any character styles that end in the word char – three of them disappear. However one style which had already gone too far and had evolved into a paragraph style remained. In addition, other styles which appeared to be problem children were not found because they ended in Char1 rather than Char. What results do you get with your damaged files?

      The immediate window results I got on my testing is shown below.

      'First Time running the macro
      Total style count: 185
      Before: See Also Char::See Also
      During: See Also Char::zTempStyle
      After: See Also Char::Normal
      Before: Heading 6 Char::Heading 6
      During: Heading 6 Char::zTempStyle
      After: Heading 6 Char::Normal
      Before: Bullet Char Char::Bullet Char
      During: Bullet Char Char::zTempStyle
      After: Bullet Char Char::Bullet
      Before: Bullet Char::Normal
      During: Bullet Char::Normal
      After: Bullet Char::Normal
      
      '===================
      'Second Time running the macro
      Total style count: 182
      Before: Bullet Char::Normal
      During: Bullet Char::Normal
      After: Bullet Char::Normal
      • #809434

        See Star post 362594 for the later version of this macro

        Hi Andrew,

        I’d only tested the posted macro on a pretty mild ‘char’-style problem document. If a document has styles that end with things like “Char 1”, then it’s not going to trap them – in that case InStr would be better (as long as one follows a style naming convention which avoids the use of the characters “Char” in any style names). Could you e-mail me a sample of a really bad problem document to take a look at?

        The core of the code came from something Cindy Meister posted on her FAQ page – tracked down the link – it is here. Her original code was this:

        Sub DeleteHeading2Char()
        Dim styl As Word.Style, doc As Word.Document
        Set doc = ActiveDocument
        Set styl = doc.Styles.Add(Name:="Style1")
        On Error Resume Next
        doc.Styles("Heading 2 Char").LinkStyle = styl
        styl.Delete
        End Sub
        

        My guess is that you need to create the temp style, only to immediately delete it, because the only way to get rid of a char style is to delete the base style that it is linked to. For that reason, you couldn’t use Normal style, since you can’t delete that. Default Paragraph Font wouldn’t work, because besides being a built-in style that you can’t delete, it is a proper Character style, whereas I think these hybrid char styles can only be linked to Paragraph styles.

        As to some of the hybrid char styles disappearing even though the code doesn’t delete them explicitly – all that’s needed to make them disappear, is to delete the paragraph style that they are linked to.

        I’ll try to track down some documents in more grievous condition and test some more.

        One other health warning that needs to go with this macro is that it is going to remove any font formatting which had been applied courtesy of the linked char style – that font formatting would therefore need to be restored manually after running the macro. It might be possible to get a macro like this, to preserve the font formatting even while deleting the linked char style, by noting the linked char style’s font properties before deleting it, creating a proper Character style to take over its function, and applying the new Character style to the affected text – while also dealing with the need to avoid creating redundant new Character styles when deleting “Body Text Char”, “Body Text Char Char” etc. – sounds like a lot of trouble!

        Gary

        PS: A very good discussion of the hybrid linked character styles problem can be found in this white paper by Microsystems.

      • #809435

        See Star post 362594 for the later version of this macro

        Hi Andrew,

        I’d only tested the posted macro on a pretty mild ‘char’-style problem document. If a document has styles that end with things like “Char 1”, then it’s not going to trap them – in that case InStr would be better (as long as one follows a style naming convention which avoids the use of the characters “Char” in any style names). Could you e-mail me a sample of a really bad problem document to take a look at?

        The core of the code came from something Cindy Meister posted on her FAQ page – tracked down the link – it is here. Her original code was this:

        Sub DeleteHeading2Char()
        Dim styl As Word.Style, doc As Word.Document
        Set doc = ActiveDocument
        Set styl = doc.Styles.Add(Name:="Style1")
        On Error Resume Next
        doc.Styles("Heading 2 Char").LinkStyle = styl
        styl.Delete
        End Sub
        

        My guess is that you need to create the temp style, only to immediately delete it, because the only way to get rid of a char style is to delete the base style that it is linked to. For that reason, you couldn’t use Normal style, since you can’t delete that. Default Paragraph Font wouldn’t work, because besides being a built-in style that you can’t delete, it is a proper Character style, whereas I think these hybrid char styles can only be linked to Paragraph styles.

        As to some of the hybrid char styles disappearing even though the code doesn’t delete them explicitly – all that’s needed to make them disappear, is to delete the paragraph style that they are linked to.

        I’ll try to track down some documents in more grievous condition and test some more.

        One other health warning that needs to go with this macro is that it is going to remove any font formatting which had been applied courtesy of the linked char style – that font formatting would therefore need to be restored manually after running the macro. It might be possible to get a macro like this, to preserve the font formatting even while deleting the linked char style, by noting the linked char style’s font properties before deleting it, creating a proper Character style to take over its function, and applying the new Character style to the affected text – while also dealing with the need to avoid creating redundant new Character styles when deleting “Body Text Char”, “Body Text Char Char” etc. – sounds like a lot of trouble!

        Gary

        PS: A very good discussion of the hybrid linked character styles problem can be found in this white paper by Microsystems.

    • #807280

      Gary

      I’m trying to understand how this code works and wondering if you really need to create a style to link to just so you can delete that style. Can’t we just link to ‘Normal’ or ‘Default Paragraph Font’ instead? I think changing the if statement to InStr might also yield more successful hits.

      I modified your code slightly to see what is happening during the run and am still puzzled on what is happening

      Public Sub RemoveAllCharCharStyles()
         Dim objDocStyles As Styles
         Dim objTempStyle As Style
         Dim StylesCt As Long
         Dim strStyleName As String
         Dim n As Long
         
         Set objDocStyles = ActiveDocument.Styles
         StylesCt = objDocStyles.count
         Debug.Print "Total style count: " & StylesCt
         On Error Resume Next
            
         For n = StylesCt To 1 Step -1
            strStyleName = objDocStyles(n).NameLocal
            If LCase$(Right$(strStyleName, 4)) = "char" Then
               Debug.Print "Before: " & strStyleName & "::" & objDocStyles(n).LinkStyle
               Set objTempStyle = objDocStyles.Add(Name:="zTempStyle")
               objDocStyles(strStyleName).LinkStyle = objTempStyle
               Debug.Print "During: " & strStyleName & "::" & objDocStyles(n).LinkStyle
               objTempStyle.Delete
               Set objTempStyle = Nothing
               Debug.Print "After: " & strStyleName & "::" & objDocStyles(n).LinkStyle
            End If
         Next 'n
         Set objDocStyles = Nothing
      End Sub

      Now when I run this code twice to compare the results, I discovered that despite the code not physically deleting any character styles that end in the word char – three of them disappear. However one style which had already gone too far and had evolved into a paragraph style remained. In addition, other styles which appeared to be problem children were not found because they ended in Char1 rather than Char. What results do you get with your damaged files?

      The immediate window results I got on my testing is shown below.

      'First Time running the macro
      Total style count: 185
      Before: See Also Char::See Also
      During: See Also Char::zTempStyle
      After: See Also Char::Normal
      Before: Heading 6 Char::Heading 6
      During: Heading 6 Char::zTempStyle
      After: Heading 6 Char::Normal
      Before: Bullet Char Char::Bullet Char
      During: Bullet Char Char::zTempStyle
      After: Bullet Char Char::Bullet
      Before: Bullet Char::Normal
      During: Bullet Char::Normal
      After: Bullet Char::Normal
      
      '===================
      'Second Time running the macro
      Total style count: 182
      Before: Bullet Char::Normal
      During: Bullet Char::Normal
      After: Bullet Char::Normal
    • #825958

      Hi Gary (et al),

      Since the LinkStyle property isn’t available in Word 2000, Gary’s macro won’t work for that version. I had long been just fixing the “char char” styles manually, but Gary’s macro prompted me to take a stab at automating it. (Actually, Gary’s macro prompted me to try and just use his macro — it was discovering to my dismay that it didn’t work on Word 2000 that actually got me doing my own coding wink .)

      This macro retains any existing aliases, and it also allows for styles whose names start with “Char”.

      I’ve tested this on a bunch of documents with “Char Char” styles, and it seemed to work pretty well. But I’d love any feedback or suggestions (or questions or complaints). I haven’t tested it on Word 2003, but will do so tonight.

      Sub Word2000DeleteCharCharStyles()
      Dim sty As Style
      Dim i As Integer
      Dim doc As Document
      Dim sStyleName As String
      Dim bCharCharFound As Boolean
      Set doc = ActiveDocument
          
      Do
          bCharCharFound = False
          For i = doc.Styles.Count To 1 Step -1
              Set sty = doc.Styles(i)
              sStyleName = sty.NameLocal
              If sStyleName Like "* Char*" Then
                  bCharCharFound = True
                  If sty.Type = wdStyleTypeCharacter Then
                      sty.Delete
                  Else
                      sty.NameLocal = Replace(sStyleName, " Char", "")
                  End If
                  Exit For
              End If
              
              Set sty = Nothing
          Next i
      Loop While bCharCharFound = True
      End Sub

      The Do…While Loop is there because renaming a style dynamically changes its location in the Styles collection. This was a quick way to accommodate that. Again, comments are welcome.

      • #826070

        Word 2000 doesn’t produce the charchar styles and I haven’t received any Word 2002 documents that have had the charchar style. Do you have one that you could post, so I could see what happens in Word 2000?
        Thanks,

        • #826086

          Hi Phil,

          I’ve attached a file that contains four styles (well, besides the defaults). “Quote,q” and its accompanying “char” style, and “>ListBullet,>lb” and its accompanying “char” style.

          I don’t know off hand which version of word these styles came from.

          Since Word 2000 doesn’t support the LinkStyle property, I’m guessing it just splits them into two styles, one paragraph and one character. Sometimes, though, there’s no character style created, just a paragraph style showing up with “char char” in the name.

          The macro I posted earlier represents the general algorithm I use to cleanse them from Word 2000: delete the character ones, and rename the paragraph ones.

          I’m at home on Word 2003 now, so can’t get a better sample for you.

          • #826088

            Thanks, Andrew. I see the problem now & I’ve copied your macro for future use.

          • #826089

            Thanks, Andrew. I see the problem now & I’ve copied your macro for future use.

            • #826096

              The original code I posted choked when I tried it on a *real* char style (one that’s actually a linked style, as opposed to the behavior I described above in Word 2000). I got a Runtime Error 4198: Command failed on the line:

               sty.Delete 

              But I noticed that, in fact, the style was deleted. Adding an On Error Resume Next line made it work like a charm.

              It’s hard to create test files for this, so if anyone’s got a really messy “char char” document, I’d love to test this on it. I’m going to (very) tentatively say this works for Word 2000+. I’d love feedback, of course.

              Sub MyDeleteCharCharStyles()
              Dim sty As Style
              Dim i As Integer
              Dim doc As Document
              Dim sStyleName As String
              Dim bCharCharFound As Boolean
              Set doc = ActiveDocument
              Do
                  bCharCharFound = False
                  For i = doc.Styles.Count To 1 Step -1
                      Set sty = doc.Styles(i)
                      sStyleName = sty.NameLocal
                      If sStyleName Like "* Char*" Then
                          bCharCharFound = True
                          If sty.Type = wdStyleTypeCharacter Then
                              On Error Resume Next
                              sty.Delete
                          Else
                              sty.NameLocal = Replace(sStyleName, " Char", "")
                          End If
                      Exit For
                      End If
                      Set sty = Nothing
                  Next i
              Loop While bCharCharFound = True
              End Sub

              P.S. / FYI — Another way to remove aliases from a style is with the split function:

              Set sty = ActiveDocument.Styles("Style Name,with,many,aliases")
              sty.NameLocal = Split(sty.NameLocal, ",")(0)
              
            • #827986

              Hi all,

              Sorry to keep resurrecting this thread, but I had a Eureka moment today, and needed to share. I was trying to figure out how to kill the Char style, but keep the formatting, and then it hit me:

              Dim rng as Range
              Dim f as Font
              ...
              Set f = rng.Font.Duplicate
              rng.Font.Reset
              rng.Font = f
              ...
              

              That removes the character style, then reapplies all the style’s formatting.

              I had this split into three separate macros, but thought a single subroutine would be (slightly) easier to follow. If anyone’s interested in the separated (and better commented versions), I can post that as well.

              The attached macro:

              (1). Deletes any “Char Char” styles
              (2). Retains the character formatting of the text that had the “Char Char” style applied
              (3). Retains any style aliases
              (4). Allows for document styles that begin with “Char”

              Another issue I’ve encountered (it usually shows up when the document’s opened in Word 2000) is that often there will be a paragraph style with “Char Char” in the name, and the original style without the “Char Char” will still be in the document. That raises an error when trying to rename the “Char Char” style. This macro takes care of that, applying the “Char-free” pun style to any text that has the “Char Char” paragraph style applied, and then deletes that style.

              I tried to make something that would work in Word 2000/97, which don’t support the LinkStyle property, but I couldn’t do it. There’s a line in the code:

              sty.LinkStyle = wdStyleNormal

              that should be commented out on Word 2000 (or you’ll get a compilation error).

              I would appreciate any feedback.

            • #834535

              Hi Andrew,

              Sorry for taking so long to get back to this thread. Your approach is very inventive!

              I haven’t had a chance to go through the code really carefully, but here are a few initial thoughts/comments:
              I’ve tested your macro on a number of very nasty specimens (all in Word 2002). For the most part, the macro did great; there was one glitch I came upon:

              At the firm where I work, aliases are intentionally used, so for example Heading 2 is “Heading 2, H2”.
              In some of the very bad sample documents I tested, the Heading 2 style featured a proliferation of aliases, along the lines of “Heading 2, Heading2 Char1, Heading 2 Char Char, H2 Char Char, H2 …” etc.
              After running your macro, the Heading 2 style still had a (shorter) trail of aliases: “Heading 2, Heading 21, H2, H21”.

              Not sure why that is happening, but I suspect it’s because the code doesn’t differentiate between built-in (paragraph) styles and non-built-in styles when it tries to delete a given style. If you try to delete a built-in style, that will raise an error, which in your code gets worked around by “On Error Resume Next”, but the result is that while the built-in style does not get deleted, neither does it get fully renamed.

              It might be that to avoid that, you’d need to add a branch which tests whether the current paragraph style is built-in or not, and handles things differently accordingly – I haven’t had a chance to try that out with this code though. In the code I posted, it tests whether the style is built-in or not; if it is built-in, it doesn’t attempt to delete the style but rather just gets rid of all aliases in the style name. In the case of these particular problem documents, the code I posted therefore works better in that it doesn’t leave all those odd aliases behind.
              (Because my firm does use specific aliases such as H1, H2 etc., I then have an extra little piece of code which puts the aliases back in for the Heading styles:

                 With ActiveDocument.Styles
                    For h = 1 To 9
                       .Item("Heading " & CStr(h)).NameLocal = _
                                                  "Heading " & CStr(h) & ",H" & CStr(h)
                    Next 'h
                 End With
              

              Anyway, it might be worth adding a test for ‘built-in’, into the part of the code that tries to delete the style.

              With regard to retaining the character formatting of the text that had the charchar style applied: this has led you to some admirably creative solutions, but I’m not sure how necessary it is: it would be useful in those instances where a user has intentionally created a charchar style to act in a manner similar to a proper character style, but at least in terms of the documents I see at work, that’s virtually never the reason that charchar styles get created: rather, they get created through applying a paragraph style, when only part of a paragraph is selected. In those cases, at least in our documents here, there really isn’t any need to preserve the char char formatting – our main concern is to get the char char style removed and the paragraph restored to a single style – if any further reformatting is necessary from that point, we’d rather examine the document manually and decide what styles need to be (properly) applied – rather than leave the document full of direct formatting, which I gather this macro will do. I guess in some different situations, users might want the font formatting preserved, but that requirement can’t be considered universal. Might it be possible to add an element of choice to the macro, so the user could indicate whether they want the char char formatting preserved as local formatting, or not?

              Only other comment is to add an “Set oDoc = Nothing” at the end.

              Your version is definitely a step forward, but per the above perhaps there is still more that could be done. If time allows this weekend, I’ll try to do some hacking….

              Gary

            • #835565

              Hi Gary,

              Thanks so much for taking this code for a test drive. I definitely appreciate the feedback. Any chance you could post a (blank) copy of one of those nasty specimens you talked about? I’d love to be able to have something really “bad” to test with while I experiment with your suggestions. In the meantime, I modifed some documents to include styles with names like the ones you encountered. It looks like it’s not an issue of built ins, it’s just inadequate string processing on my part. I never tested with numerals appended to the “char” (Char1, char2, etc.).

              The snippet below replaces the more elegant, but inadequate Replace call with some cumbersome but effective good old-fashioned string functions. What I wouldn’t give for built-in regular expressions and variable interpolation!

              As for retaining the character formatting, I agree with you on its questionable necessity, but did want to offer it at least as an option.

              ' Replace this line:
              'sStyleReName = Replace(sStyleName, " Char", "")
              '
              ' with this block (new variables declared here for easier reading)
              '
                              Dim k As Integer
                              Dim lPos As Long
                              Dim var As Variant
                              var = Split(sStyleName, ",")
                              For k = 0 To UBound(var)
                                  lPos = InStr(var(k), " Char")
                                  If lPos  0 Then
                                      var(k) = Left(var(k), lPos - 1)
                                  End If
                              Next k
                              sStyleReName = Join(var, ",")
              

              A more compact, but less readable version without using the lPos variable would be:

              ...
              For k = 0 to UBound(var)
                  If InStr(var(k), " Char")  0 Then var(k) = Left(var(k), (InStr(var(k), " Char")) - 1)
              Next k
              ...
              

              As an aside for anyone interested, note that even if you’ve set your array base explicitly to 1, variant arrays populated with the Split function are always 0-based. Ditto for using the Array function.

              Thanks again, Gary!

            • #836286

              Andrew,

              Have just tested your revised code on one of my torture documents, and it’s done a great job! thumbup
              It may not be feasible for me to post any sample documents here, but give me a couple of days and I will try to send you some privately.

              Gary

            • #836287

              Andrew,

              Have just tested your revised code on one of my torture documents, and it’s done a great job! thumbup
              It may not be feasible for me to post any sample documents here, but give me a couple of days and I will try to send you some privately.

              Gary

            • #835566

              Hi Gary,

              Thanks so much for taking this code for a test drive. I definitely appreciate the feedback. Any chance you could post a (blank) copy of one of those nasty specimens you talked about? I’d love to be able to have something really “bad” to test with while I experiment with your suggestions. In the meantime, I modifed some documents to include styles with names like the ones you encountered. It looks like it’s not an issue of built ins, it’s just inadequate string processing on my part. I never tested with numerals appended to the “char” (Char1, char2, etc.).

              The snippet below replaces the more elegant, but inadequate Replace call with some cumbersome but effective good old-fashioned string functions. What I wouldn’t give for built-in regular expressions and variable interpolation!

              As for retaining the character formatting, I agree with you on its questionable necessity, but did want to offer it at least as an option.

              ' Replace this line:
              'sStyleReName = Replace(sStyleName, " Char", "")
              '
              ' with this block (new variables declared here for easier reading)
              '
                              Dim k As Integer
                              Dim lPos As Long
                              Dim var As Variant
                              var = Split(sStyleName, ",")
                              For k = 0 To UBound(var)
                                  lPos = InStr(var(k), " Char")
                                  If lPos  0 Then
                                      var(k) = Left(var(k), lPos - 1)
                                  End If
                              Next k
                              sStyleReName = Join(var, ",")
              

              A more compact, but less readable version without using the lPos variable would be:

              ...
              For k = 0 to UBound(var)
                  If InStr(var(k), " Char")  0 Then var(k) = Left(var(k), (InStr(var(k), " Char")) - 1)
              Next k
              ...
              

              As an aside for anyone interested, note that even if you’ve set your array base explicitly to 1, variant arrays populated with the Split function are always 0-based. Ditto for using the Array function.

              Thanks again, Gary!

            • #834536

              Hi Andrew,

              Sorry for taking so long to get back to this thread. Your approach is very inventive!

              I haven’t had a chance to go through the code really carefully, but here are a few initial thoughts/comments:
              I’ve tested your macro on a number of very nasty specimens (all in Word 2002). For the most part, the macro did great; there was one glitch I came upon:

              At the firm where I work, aliases are intentionally used, so for example Heading 2 is “Heading 2, H2”.
              In some of the very bad sample documents I tested, the Heading 2 style featured a proliferation of aliases, along the lines of “Heading 2, Heading2 Char1, Heading 2 Char Char, H2 Char Char, H2 …” etc.
              After running your macro, the Heading 2 style still had a (shorter) trail of aliases: “Heading 2, Heading 21, H2, H21”.

              Not sure why that is happening, but I suspect it’s because the code doesn’t differentiate between built-in (paragraph) styles and non-built-in styles when it tries to delete a given style. If you try to delete a built-in style, that will raise an error, which in your code gets worked around by “On Error Resume Next”, but the result is that while the built-in style does not get deleted, neither does it get fully renamed.

              It might be that to avoid that, you’d need to add a branch which tests whether the current paragraph style is built-in or not, and handles things differently accordingly – I haven’t had a chance to try that out with this code though. In the code I posted, it tests whether the style is built-in or not; if it is built-in, it doesn’t attempt to delete the style but rather just gets rid of all aliases in the style name. In the case of these particular problem documents, the code I posted therefore works better in that it doesn’t leave all those odd aliases behind.
              (Because my firm does use specific aliases such as H1, H2 etc., I then have an extra little piece of code which puts the aliases back in for the Heading styles:

                 With ActiveDocument.Styles
                    For h = 1 To 9
                       .Item("Heading " & CStr(h)).NameLocal = _
                                                  "Heading " & CStr(h) & ",H" & CStr(h)
                    Next 'h
                 End With
              

              Anyway, it might be worth adding a test for ‘built-in’, into the part of the code that tries to delete the style.

              With regard to retaining the character formatting of the text that had the charchar style applied: this has led you to some admirably creative solutions, but I’m not sure how necessary it is: it would be useful in those instances where a user has intentionally created a charchar style to act in a manner similar to a proper character style, but at least in terms of the documents I see at work, that’s virtually never the reason that charchar styles get created: rather, they get created through applying a paragraph style, when only part of a paragraph is selected. In those cases, at least in our documents here, there really isn’t any need to preserve the char char formatting – our main concern is to get the char char style removed and the paragraph restored to a single style – if any further reformatting is necessary from that point, we’d rather examine the document manually and decide what styles need to be (properly) applied – rather than leave the document full of direct formatting, which I gather this macro will do. I guess in some different situations, users might want the font formatting preserved, but that requirement can’t be considered universal. Might it be possible to add an element of choice to the macro, so the user could indicate whether they want the char char formatting preserved as local formatting, or not?

              Only other comment is to add an “Set oDoc = Nothing” at the end.

              Your version is definitely a step forward, but per the above perhaps there is still more that could be done. If time allows this weekend, I’ll try to do some hacking….

              Gary

            • #827987

              Hi all,

              Sorry to keep resurrecting this thread, but I had a Eureka moment today, and needed to share. I was trying to figure out how to kill the Char style, but keep the formatting, and then it hit me:

              Dim rng as Range
              Dim f as Font
              ...
              Set f = rng.Font.Duplicate
              rng.Font.Reset
              rng.Font = f
              ...
              

              That removes the character style, then reapplies all the style’s formatting.

              I had this split into three separate macros, but thought a single subroutine would be (slightly) easier to follow. If anyone’s interested in the separated (and better commented versions), I can post that as well.

              The attached macro:

              (1). Deletes any “Char Char” styles
              (2). Retains the character formatting of the text that had the “Char Char” style applied
              (3). Retains any style aliases
              (4). Allows for document styles that begin with “Char”

              Another issue I’ve encountered (it usually shows up when the document’s opened in Word 2000) is that often there will be a paragraph style with “Char Char” in the name, and the original style without the “Char Char” will still be in the document. That raises an error when trying to rename the “Char Char” style. This macro takes care of that, applying the “Char-free” pun style to any text that has the “Char Char” paragraph style applied, and then deletes that style.

              I tried to make something that would work in Word 2000/97, which don’t support the LinkStyle property, but I couldn’t do it. There’s a line in the code:

              sty.LinkStyle = wdStyleNormal

              that should be commented out on Word 2000 (or you’ll get a compilation error).

              I would appreciate any feedback.

            • #826097

              The original code I posted choked when I tried it on a *real* char style (one that’s actually a linked style, as opposed to the behavior I described above in Word 2000). I got a Runtime Error 4198: Command failed on the line:

               sty.Delete 

              But I noticed that, in fact, the style was deleted. Adding an On Error Resume Next line made it work like a charm.

              It’s hard to create test files for this, so if anyone’s got a really messy “char char” document, I’d love to test this on it. I’m going to (very) tentatively say this works for Word 2000+. I’d love feedback, of course.

              Sub MyDeleteCharCharStyles()
              Dim sty As Style
              Dim i As Integer
              Dim doc As Document
              Dim sStyleName As String
              Dim bCharCharFound As Boolean
              Set doc = ActiveDocument
              Do
                  bCharCharFound = False
                  For i = doc.Styles.Count To 1 Step -1
                      Set sty = doc.Styles(i)
                      sStyleName = sty.NameLocal
                      If sStyleName Like "* Char*" Then
                          bCharCharFound = True
                          If sty.Type = wdStyleTypeCharacter Then
                              On Error Resume Next
                              sty.Delete
                          Else
                              sty.NameLocal = Replace(sStyleName, " Char", "")
                          End If
                      Exit For
                      End If
                      Set sty = Nothing
                  Next i
              Loop While bCharCharFound = True
              End Sub

              P.S. / FYI — Another way to remove aliases from a style is with the split function:

              Set sty = ActiveDocument.Styles("Style Name,with,many,aliases")
              sty.NameLocal = Split(sty.NameLocal, ",")(0)
              
        • #826087

          Hi Phil,

          I’ve attached a file that contains four styles (well, besides the defaults). “Quote,q” and its accompanying “char” style, and “>ListBullet,>lb” and its accompanying “char” style.

          I don’t know off hand which version of word these styles came from.

          Since Word 2000 doesn’t support the LinkStyle property, I’m guessing it just splits them into two styles, one paragraph and one character. Sometimes, though, there’s no character style created, just a paragraph style showing up with “char char” in the name.

          The macro I posted earlier represents the general algorithm I use to cleanse them from Word 2000: delete the character ones, and rename the paragraph ones.

          I’m at home on Word 2003 now, so can’t get a better sample for you.

      • #826071

        Word 2000 doesn’t produce the charchar styles and I haven’t received any Word 2002 documents that have had the charchar style. Do you have one that you could post, so I could see what happens in Word 2000?
        Thanks,

    • #825959

      Hi Gary (et al),

      Since the LinkStyle property isn’t available in Word 2000, Gary’s macro won’t work for that version. I had long been just fixing the “char char” styles manually, but Gary’s macro prompted me to take a stab at automating it. (Actually, Gary’s macro prompted me to try and just use his macro — it was discovering to my dismay that it didn’t work on Word 2000 that actually got me doing my own coding wink .)

      This macro retains any existing aliases, and it also allows for styles whose names start with “Char”.

      I’ve tested this on a bunch of documents with “Char Char” styles, and it seemed to work pretty well. But I’d love any feedback or suggestions (or questions or complaints). I haven’t tested it on Word 2003, but will do so tonight.

      Sub Word2000DeleteCharCharStyles()
      Dim sty As Style
      Dim i As Integer
      Dim doc As Document
      Dim sStyleName As String
      Dim bCharCharFound As Boolean
      Set doc = ActiveDocument
          
      Do
          bCharCharFound = False
          For i = doc.Styles.Count To 1 Step -1
              Set sty = doc.Styles(i)
              sStyleName = sty.NameLocal
              If sStyleName Like "* Char*" Then
                  bCharCharFound = True
                  If sty.Type = wdStyleTypeCharacter Then
                      sty.Delete
                  Else
                      sty.NameLocal = Replace(sStyleName, " Char", "")
                  End If
                  Exit For
              End If
              
              Set sty = Nothing
          Next i
      Loop While bCharCharFound = True
      End Sub

      The Do…While Loop is there because renaming a style dynamically changes its location in the Styles collection. This was a quick way to accommodate that. Again, comments are welcome.

    Viewing 5 reply threads
    Reply To: Macro to Delete CharChar styles (Word 2002)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: