简体   繁体   中英

How to loop a MS Word macro applying word by word in a selection?

I have a simple macro in order to insert a symbol into the front and back of a word.

Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1

Is there any way to make the macros looping through each word in the selection of text?

You can do something like this:

Dim myRangeIndex As Range
Dim myRangeStart As Range

Set myRangeStart = Selection.Range

For Each myRangeIndex In myRangeStart.Words()

   myRangeIndex.Select

   Selection.MoveLeft Unit:=wdWord, Count:=1
   Selection.TypeText Text:="a"
   Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
   Selection.Font.Color = -603914241
   Selection.Font.Size = 1
   Selection.MoveRight Unit:=wdWord, Count:=1
   Selection.MoveLeft Unit:=wdWord, Count:=1
   Selection.MoveRight Unit:=wdWord, Count:=1
   Selection.MoveLeft Unit:=wdCharacter, Count:=1
   Selection.TypeText Text:="a"
   Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
   Selection.Font.Color = -603914241
   Selection.Font.Size = 1
   Selection.MoveRight Unit:=wdCharacter, Count:=1
   Selection.MoveRight Unit:=wdWord, Count:=1

Next myRangeIndex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM