Consulting

Results 1 to 5 of 5

Thread: Getting character after / to capitalize

  1. #1
    VBAX Mentor
    Joined
    Aug 2020
    Location
    Hampshire
    Posts
    395
    Location

    Getting character after / to capitalize

    I've been scratching my head trying to get the following to detect any '/' that appears as a second character, then to capitalize the character immediately after it, which will be at position three.

    If I use this as an example and capitalize the third character if it finds a 'c' at position two, then it works okay.

    If oCtrl.Name = "txtVictim" Then
                            strTC = strConv(oCtrl.Text, vbProperCase)
                            Set oCC = ActiveDocument.SelectContentControlsByTag("Victim").Item(1)
                            oCC.Range.Text = strTC
                            For lngIndex = 1 To oCC.Range.Words.Count
                                If oCC.Range.Words(lngIndex).Characters(2) = "c" Then
                                    oCC.Range.Words(lngIndex).Characters(3) = UCase(oCC.Range.Words(lngIndex).Characters(3))
                                End If
                            Next
    If I change from 'c' to a '/' or char (47), then I get a Runtime error '5941' - The requested member of the collection does not exist on this line.

    If oCC.Range.Words(lngIndex).Characters(2) = "/" Then

  2. #2
    Because of the way 'words' are defined "/" is a word in its own right so cannot have two characters, hence the error.
    If you want to capitalise after "/" then you will need to do it another way e.g.

    Set oWrd = oCC.Range
        With oWrd.Find
            Do While .Execute(findText:="/")
                If oWrd.InRange(oCC.Range) Then
                    oWrd.Next.Characters(1).Case = wdUpperCase
                End If
                oWrd.Collapse 0
            Loop
        End With
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    VBAX Mentor
    Joined
    Aug 2020
    Location
    Hampshire
    Posts
    395
    Location
    Thank you, Graham.

    I would never have figured on a "/" being a word!

    Is this the same for other characters such as "-", "#" and "&" etc.?

  4. #4
    If in doubt use the following macro to list the words in the selected string in the immediate window

    Sub Words()
    Dim i As Integer
        For i = 1 To Selection.Words.Count
    Debug.Print Selection.Words(i)
        Next i
    End Sub
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  5. #5
    VBAX Mentor
    Joined
    Aug 2020
    Location
    Hampshire
    Posts
    395
    Location
    Lovely, thanks again Graham.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •