PDA

View Full Version : Changing a character case based on its style



hoggm2
03-26-2019, 03:27 PM
Hi,
My objective is to change the first letter of a list of bullets to uppercase. I have tried both the selection and range functions to do this. The problem is that the while loop seems to not be looping. I may be missing something obvious, but I am just not seeing it. Advice/guidance appreciated!

Thanks, Martin


Sub test2()

Selection.HomeKey wdStory
CapitaliseFirstChar ("List Bullet")

End Sub



Sub CapitaliseFirstChar(Style As String)

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

With Selection.Find
.Text = SearchString
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Style = ActiveDocument.Styles(Style)
End With

Selection.Find.Execute
While Selection.Find.Found
Selection.Select
Set oRng = Selection.Range
oRng.Characters(1) = UCase(oRng.Characters(1))
Wend

End Sub

gmayor
03-26-2019, 09:45 PM
Try this

Sub test3()
CapitaliseFirstChar ("List Bullet")
End Sub


Sub CapitaliseFirstChar(strStyle As String)
Dim oPara As Paragraph
For Each oPara In ActiveDocument.Range.Paragraphs
If oPara.Style = strStyle Then
oPara.Range.Characters(1).Case = wdUpperCase
End If
Next oPara
lbl_Exit:
Set oPara = Nothing
Exit Sub
End Sub

hoggm2
03-27-2019, 12:12 PM
Thank you Graham, very much appreciated. And from the your code I can now see how to undertake this type of task more effectivly.

Kind Regards

Martin

gmaxey
03-28-2019, 05:55 AM
Martin,

I don't want to be critical of Graham's solution and only coming back to post because I was hitting a continuous loop yesterday while testing a Find method and had to exit for a night class. I'm sure that in the vast majority of cases that looping through each paragraph of a document for this sort of requirement would hardly be noticeable and when anything works, of course it appears efficient. But, if the text were say "War and Peace" then it might take awhile ;-).

Another thing, when working with find and replace, using a range object is usually cleaner than using Selection.


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Style = "List Bullet"
.Wrap = wdFindStop
Do While .Execute
oRng.Characters(1).Case = wdUpperCase
oRng.Collapse wdCollapseEnd
If oRng.End = ActiveDocument.Range.End - 1 Then Exit Do
Loop
End With
lbl_Exit:
Exit Sub
End Sub


Note: Due to the fickleness of the find method, the continuous loop would occur without the line "If oRng.End = ActiveDocument.Range.End - 1 Then Exit Do" should the last line of the document be formatted with List Bullet style.

hoggm2
03-28-2019, 10:21 AM
Thank you Greg, that's helpful, and may be useful for some more manipulation I need to do based on styles. Some months ago I purchsed Word Tips:The Mcros, for which I recognise your name! Great reference material.
Kind Regards
Martin