• Grouping of Characters Macro

    Author
    Topic
    #354614

    I suspect this will be a no-brainer for many of you, but it has me scratching my head (never done a macro in Word yet, but very eager to learn!)

    What I’d like to be able to do is select a series of characters in the document (such as ‘ajskdlfajskdlfa’) and then trigger a macro that would automatically insert one space after every three characters, for the duration of the selected range. Using the example again, the result would be ‘ajs kdl faj skd lfa’.

    Would anyone be able to get me started in the right direction?

    Thanks!

    Viewing 1 reply thread
    Author
    Replies
    • #521312

      Is the style of the text important to preserve? If not, you could read the selection into variable, insert the needed spaces, and replace the selection with that. I’m sure someone has some time to put that together. (The fun part is the math.)

      On the other hand, if you need to preserve the style of the text, or maybe even if you don’t, the other approach would be to get a sense of where the beginning and end of the selection are, then, starting from the beginning, move the insertion point right three spaces and type a space, repeating until you exit your original selection. One way to do this is to mark your selection with a bookmark, and then check to see if you are past the end of the bookmark before typing a space and, if you are, stop and delete the bookmark (not the contents, just the bookmark). This stuff-happening-on-screen approach is generally slower to execute, but if your selections are not very big, the difference won’t matter.

      Hope this at least gives you some ideas.

    • #521316

      How about something along these lines

      Sub Macro2()
      Dim x As Long
      x = Selection.Range.Characters.count
      While x / 3 > 1
        Selection.Characters(3).InsertAfter " "
        Selection.MoveStart Unit:=wdCharacter, count:=4
        x = Selection.Range.Characters.count
      Wend
      End Sub
      • #521355

        Thank you both for the help on this one! The sample code worked like a charm – and provides a great starting point for me to do some more VBA exploring on my own!

        Cheers,

        Trevor.

    Viewing 1 reply thread
    Reply To: Grouping of Characters Macro

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

    Your information: