PDA

View Full Version : Replacing string with bold



mcwsky09
03-27-2012, 08:33 AM
I have a document in which I am currently using the following code:


For x = 1 To 25 Step 1
WordBasic.EditReplace Find:="****", PatternMatch:=0, Wrap:=0

' Selection.Find.Execute
Selection.MoveUp Unit:=wdParagraph, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Selection.Font.Bold = wdToggle
Selection.MoveDown Unit:=wdParagraph, Count:=1
Next


to set every line which starts with a string of asterisks to bold.
there is not always the same number of such lines - so I would prefer to have more efficient code that either first checks to see how many occurrences there are and then loops as needed - or even better can search and replace the text with bold text.

each line looks something like this:
***************** HEADER 1 ***************
*************** HEADER 222 ******************

there is not a specific number asterisks - and the text is different in each one - though on larger files each header might be repeated a number of times.

so I need code that either tags the beginning and end or can search for literal asterisk while also using the * as a wild card - each header is a full paragraph.

I have a manual Search and Replace using a null replace that does what I want - but when I record a macro and run it - instead of replacing the text with the same text - it gets replaced with null.

actually - just occurred to me - that perhaps all I need to do is replace only the asterisks with bold asterisks - even if the text is not bolded - the asterisks being bolded might be sufficient.

or perhaps I should take the time to enumerate all the possible headers and choose unique colors for each of them.

Talis
03-27-2012, 09:44 AM
Not sure what you mean by "tags the beginning and end".
But try this as a start:
Sub ChangeAsterisksToBold()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = True
.Text = "\*[!^13]@^13"
.Replacement.ClearFormatting
.Replacement.Font.Bold = True
.Replacement.Text = "^&"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub

mcwsky09
03-27-2012, 10:33 AM
Not sure what you mean by "tags the beginning and end".
But try this as a start:
Sub ChangeAsterisksToBold()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = True
.Text = "\*[!^13]@^13"
.Replacement.ClearFormatting
.Replacement.Font.Bold = True
.Replacement.Text = "^&"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub




Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "*"
.Replacement.Text = "*"
.Forward = True
.Wrap = wdFindContinue
.Replacement.Font.Bold = True
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

also works - at least for the moment - although it is no faster than what I had before.

what I meant by tags - was something that I could insert at the beginning and end of each line to use in combination with a wild card search to find everything inclusive and change it to bold without change the string - just the format.

Talis
03-27-2012, 12:38 PM
to set every line which starts with a string of asterisks to bold.
and
to find everything inclusive and change it to bold without change the string
but if now you only want to change the asterisks to bold your macro will work.
For a long document you may want to try this for speed:
Sub ChangeOnlyAsterisksToBold()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = False
.Text = "*"
.Replacement.ClearFormatting
.Replacement.Font.Bold = True
.Replacement.Text = "^&"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub

mcwsky09
03-27-2012, 01:32 PM
that could work - but I discovered that also had another bit of code that also reduced the number of asterisks since the lines end up wrapping so I combined two portions of code into one as follows:



Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "\*{30,50}"
.Replacement.Text = "*****************************"
.Replacement.Font.Bold = True
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting


When I stumbled across the {} and found the literal notation for literal \*

I still may do something different - the main goal at the moment it to get a macro that on Word for Windows runs in less than 2 seconds but takes over 4 seconds to run on Word for Mac to take less time to complete.

Every search and replace I execute - even if it doesn't find anything - even on an empty file - takes time. In my particular case I have found some operations that are no longer needed. Before I started updating it was taking around 8 seconds to run on a large file - got it down to under 4.

Talis
03-27-2012, 01:58 PM
I am waiting for fumei to tell you that you should be using heading styles rather than bold; however, if you are not dealing with the full paragraph then that is not a good option. If you do revert to full paragraphs here's the code using style:
Sub ChangeAsterisksToBold()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = True
.Text = "\*[!^13]@^13"
.Replacement.ClearFormatting
.Replacement.Style = ActiveDocument.Styles("Heading 2")
.Replacement.Text = "^&"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub

Talis
03-27-2012, 03:11 PM
Consider this as a possibility:
Sub ChangeAsterisksToBold2()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = True
.Text = "[\*]{1,}([!\*]@)[\*]{1,}"
.Replacement.ClearFormatting
.Replacement.Style = ActiveDocument.Styles("Heading 2")
.Replacement.Text = "***\1***"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub

On the line: .Replacement.Text = "***\1***" you can change the three asterisks to how many you want.
With a bit more work you could calculate the number of characters of actual text, subtract that from a guesstimate of number of characters in a line allowing a good margin, halve that and add a STRING of asterisks before and after the text.
Although can't help wondering why you would want to retain the asterisks when you have the text standing out using bold, or better still, a heading style.

macropod
03-27-2012, 03:23 PM
I am waiting for fumei to tell you that you should be using heading styles rather than bold
You should be using heading Styles rather than hard formatting. That's what Styles are for!

fumei
03-27-2012, 04:13 PM
....ahem.....

mcwsky09
03-28-2012, 05:40 AM
I am waiting for fumei to tell you that you should be using heading styles rather than bold; however, if you are not dealing with the full paragraph then that is not a good option. If you do revert to full paragraphs here's the code using style:
Sub ChangeAsterisksToBold()
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWildcards = True
.Text = "\*[!^13]@^13"
.Replacement.ClearFormatting
.Replacement.Style = ActiveDocument.Styles("Heading 2")
.Replacement.Text = "^&"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
End Sub

I might not use Heading 2 - maybe Heading 1 - but I do like that code - thanks.

fumei
03-28-2012, 10:44 AM
Heading 1, Heading 2....YUCK!

I NEVER use the built-in heading styles.

mcwsky09
03-28-2012, 12:07 PM
Heading 1, Heading 2....YUCK!

I NEVER use the built-in heading styles.

While I agree that depending on built in styles is not ideal - I am looking for speed - so maybe I should define my own style and then use that.

unless there is a better - faster way - to accomplish what I want.

I have cut the overall macro time in about half - but it is still taking 2 seconds or more to run even on small files on Mac - compared to two tenths of second to run the same macro on the same file on Windows.

Paul_Hossler
03-29-2012, 12:22 PM
Heading 1, Heading 2....YUCK!
I NEVER use the built-in heading styles.


"A style by any other name"

There's a fair number of built in styles that I'd guess you would use, TOC1, TOC2, ....

I do create my own styles sometimes to do heading-type roles:

"Topic", 'Sub-Topic", "Main Point", ....

What's the concern about the built in Heading styles?

Paul

Frosty
03-29-2012, 02:49 PM
I believe fumei is expressing a preference for one particular way to approach the entire concept of working with styles. I think, when you boil the fat off, the two approaches are: 1) use as many custom styles and naming conventions as you can, and use built-in styles if you absolutely have to; and 2) use as many built-in styles as you can, create custom styles only if you absolutely have to.

And then two alternatives on the "when to create styles" question: 1) create "descriptor" styles (where the style name actually describes what the style does, so that styles are used as a formatting macro of sorts, but relatively static formatting across the documents your company uses ex: style named Body Text .5 Indent, Body Text 1" Indent; and 2) create "Bucket styles" (where the style describes when to be used, but not necessarily particular formatting) ex: Body Text, Body Text 2.

I've worked with both "systems" (such as they are), and I honestly don't think there is one which is better. I think some of the reasons to always use styles are becoming less with the newer versions of Word...

I remember that most of the preferences usually revolved around a particular user's experience with a bug which may or may not have been fixed in a specific version of Word... but I always love to get more info...

Would that articulate the general approaches, Fumei? Would love to hear your arguments for your style approach preference.

fumei
03-29-2012, 05:16 PM
Yes, I would agree that those are the two basic approaches. I would also agree that it is debatable which is "better".

What is NOT debatable (IMO) is the strongest need to be consistent. I use both approaches, and even combinations. I want to add a crucial point, in that the use of styles without the use of (real) templates, diminishes the value of either/both.

I also would add that the "when to create styles" is not (in my case) is not dependent on either descriptor or Bucket alternative. It is 100% practical.

And for the record, after a career that produced 1000's of documents, not one of them has a single instance of Normal. EVERY paragraph has a defined style.

Paul, yes, TOC styles are used, but I attach different format to them. They show as (for example) TOC1,Finance in the Table of Contents dialog.

Jason: "I think some of the reasons to always use styles are becoming less with the newer versions of Word..."

Please expand on this.

Frosty
03-29-2012, 05:41 PM
I agree with your point about use of styles without templates diminishing the value of both.
A function like "Select Text With Similar Formatting" conceptually (if not yet practically) removes one of the reasons to use styles (the ability to reformat non-contiguous areas of the document with the same formatting).

Big-picture view: the use of styles is to make it easier/quicker to reformat a document, as well as work with multiple documents (and content from those documents) all using the same approach to styles.

Simplified: if you do it right, you can change the look of a document in literally a couple of clicks, and you can paste text from another document without doing anything beyond just pasting (no reformatting necessary). But in practical application, this is rarely the result.

Getting to that level of ease of document format manipulation requires training, a consistent use of styles, and well-designed templates.

Just like we're all professional singers in the shower, everyone's document is perfect... until it goes outside of the sandbox. At that point, you have to evaluate the cost-benefit to raising the training level of an entire user-base. Because just one untrained user in the life-cycle of a document can wreak havoc on the most perfect combination of style system and template design.

So while I still appreciate the document which doesn't use the normal anywhere, I wonder if that is beginning to be at cross-purposes with the direction Microsoft is taking their design approach.

Style sets and themes allow an even more macro (not the VBA variety) approach to document formatting (and re-formatting). My suspicion is that actual style use (always hard to train people up to a good level of understanding) is becoming less important, apart from actual template design and supporting macro (of the VBA variety) creation.

But for actual use of the document by the most common level of end-user... I question how important good style usage is now (in Word 2010, at least--2003 and prior, I think it's impossible to have good documents without a good style system).

This is represents my currently-evolving nebulous opinion, rather than something I've actually decided.

Frosty
03-29-2012, 05:54 PM
And just a quick follow up-- this is all in context of me having spent the last year working with 2010, and still trying to understand some of the design decisions. I'm still learning.

But I understood Word 97, Word 2000, and Word 2003 (to a lesser extent, but it didn't change from 2000 all that much) probably as well as anyone in the business in the late 90's early 00's.

I've been in somewhat of the same "pool" since 2001, so my closed-loop understanding has been a bit more static since then-- one of the reasons why I started participating here: to learn from you all.

I appreciate having the occasional (slight) hijack of a thread in the name of better understanding-- and this is, after all, still somewhat of a continuing of the concepts talked about in the OP's original problem.

fumei
03-29-2012, 07:37 PM
Themes? Seriously? No offense, but give me a break. They can be messed up by the majority of incompetent users as much as styles.

Does it sound like I am down on users? Yes, somewhat. After 30 years of trying, yup, it sure is hard to train up users. I am glad to not being doing that any more.

I do not think it is Word styles fault however. I found that the majority of users still do not grasp files or folders either.

Sorry, but we are going to have to disagree about 2010. I think it is a moronic version and a poor step backwards. However, that will also make it work very well for most people, and will be quite sucessful.

I have 2010, but never use it as I see no advantage whatsoever, and plenty of disadvantages.

fumei
03-29-2012, 08:33 PM
I realize I showed my extreme bias against 2010 I admit it. I dislike it so much that I turned down an offer of $400 a day as the chief consultant for the transition to Office 2010, from my former employer. Apparently it is going very very badly.

Ha!

Frosty
03-29-2012, 09:24 PM
Well, you get to keep that bias... if I recall correctly, you're retired :)
Some of us, however, still have to live in the world as it exists ;)

So I'm trying to find the good and bad about Office 2010... and anticipate where MS is going in a (probably vain) attempt not to paint myself into any design corners

But still learning... appreciate your comments, biased or unbiased :)

fumei
03-29-2012, 10:03 PM
Yup. My bias shows brightly. I have taken two small Word jobs since I retired. Both were trying to fix messups because of the radical changes in 2010. I imagine there will be a few more of those for the next while.

Paul_Hossler
03-30-2012, 12:22 PM
But there is no hard and fast rule (usually) for doing things one way or another.

"There is no right way or wrong way, only appropriate and inapproiate ways"

Yes, 2010 does have it's little quirks. So did 2007, and so did 2003.

IMHO, 2010 is not targeted for the 10% of the power users who use 90% of it's capabilies (like the people who hang out here :hi: ), but for the other 90% who use 10% (maybe) of it's capabiliteis.

Real templates and proper use of styles is a great time saver, but when a 90% type user 'edits' the document, I know I'll have to spend time to streighten it out.

Themes and StyleSets probably have their place. It's unlikely that I'd ever use them for a 'significant' document, but for a 'On vacation, call Gerry for help' memo I might. Usually, 'Paul-formatted' styles will work for me better

I don't think that most of the 90% users even know that Themes exist.

As a matter of fact, people are amazed when I show them how even a simple AutoText is a huge time saver, and that's been around for ages.

Paul

PS: I'm still waiting for the publication of "Word the Right Way" by fumei :clap:

fumei
03-30-2012, 04:04 PM
PS: I'm still waiting for the publication of "Word the Right Way" by fumei

How could happen when...

"There is no right way or wrong way, only appropriate and inapproiate ways"

Besides, I am rapidly becoming a dinosaur, and you know what happened to them.

Frosty
04-02-2012, 08:43 AM
Well, as a former trainer... I'm always thinking of ways of introducing people to styles. Styles as a format macro is one approach which has been successful. Less successful is the "theory" about how much easier it is to modify a "good" document than a "bad" document.

"But it takes more time to do it right." is the standard comment.

If nothing else... demonstrating the proper usage of themes and style sets can be a more concrete way of demonstrating the power of styles. And they are better than their conceptual ancestor: auto format. :)

fumei
04-02-2012, 11:28 AM
And they are better than their conceptual ancestor: auto format.

Like a Ferrari is better than a Model T.

Paul_Hossler
04-02-2012, 02:22 PM
And they are better than their conceptual ancestor: auto format.

Like a Ferrari is better than a Model T.

It takes a lot more skill and training and experience to effectively drive a Ferrari than it does to drive a Model-T.

Paul

fumei
04-02-2012, 06:55 PM
LOL,,,VERY true!

mcwsky09
04-07-2012, 06:02 PM
It takes a lot more skill and training and experience to effectively drive a Ferrari than it does to drive a Model-T.

Paul

While there might be some room for interpretation regarding the word "effectively" but I would hazard a guess that not too many folks alive today even know how to start a Model T and that the the skill set to safely operate a Model T for any length of time is greater than that required to drive a Ferrari.

On the other hand - aside from the technical aspects - it may be true that it takes considerably more skill to drive a Ferrari to the limit of the Ferrari's capability than to do the same with a Model T.


In the case of my original post - regarding making something bold - I have ended up taking a different approach which I may have subsequently rendered obsolete by automating the process by which the data is extracted rather than just highlighting the sections for the user to extract manually.



Sub CSVBold()
'
' Headers
'
Dim Header_Item(13) As String

'Include these
Header_Item(1) = "HARDWARE"
Header_Item(2) = "HARDWARE COMMON MES"
Header_Item(3) = "HARDWARE UPGRADE FEATURE CONVERSION"
Header_Item(4) = "SOFTWARE"
Header_Item(5) = "SOFTWARE TO BE INSTALLED"

'Exclude these
Header_Item(6) = "HARDWARE BASE SYSTEM"
Header_Item(7) = "HARDWARE TARGET SYSTEM"
Header_Item(8) = "SOFTWARE BASE SYSTEM"
Header_Item(9) = "SOFTWARE TARGET SYSTEM"
Header_Item(10) = "SERVICES"
Header_Item(11) = "ERROR AND WARNING MESSAGES"
Header_Item(12) = "USER SELECTED/CRITICAL MESSAGES"
Header_Item(13) = "GRAND TOTALS"
'
Columns("A:A").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=IF(LEFT(A1,4)=""****"",TRUE,FALSE)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetLastPriorit y
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.ColorIndex = 1
End With


For i = 1 To 5
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=IF(TRIM(SUBSTITUTE(A1,""*"",""""))=""" & Header_Item(i) & """,TRUE,FALSE)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriori ty
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.ColorIndex = 11
End With
Next i

For e = 6 To 13
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=IF(TRIM(SUBSTITUTE(A1,""*"",""""))=""" & Header_Item(e) & """,TRUE,FALSE)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriori ty
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.ColorIndex = 3
End With
Next e


Range("A1").Select


Application.ScreenUpdating = True

End Sub




to use this code you would obviously change the strings to be found - and since it uses many conditional formatting rules - it is not compatible with older versions of Excel that allow only 3.

although in retrospect - I likely should have either left a gap in the array index between included and excluded items - in case i need to add more - or simply use two separate arrays would likely be even better - and code that counts the number of members in the array instead of fixed numbers would make the code more portable

the .ColorIndex I used is Blue and Red - Blue for included and Red for excluded.

the code i wrote that makes this obsolete - adds a column that checks the header and copies a tag down then removes rows to be excluded - this code uses a named range with the Include and Exclude tags set such that the code does not need to be updated if and when the list is updated. I suppose I could simply search on the entire string including the asterisks - not sure if that would be faster or not - but it seems to work well enough.

the Substitute and Trim commands really helped me in this case.

The entire thing is still a work in progress - and I may end having to pretty much scarp the entire thing in order to merge it with a separately developed spreadsheet that has a lot of overlapping capability.

Now if I could just figure out how to get code that executes in less than 1 second under Windows to do exactly the same thing on exactly the same file in less than 10 seconds on the Mac - that would be awesome.