VBA Macro to Add Text on End Of Selected Text

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Hi
I am fairly confident with Excel VBA. I have virtually no experience with Word VBA, but usually get by with a Macro recorder.
The following I could not seem to get the Macro recorder to do. It does not seem to let me make a selection??. However if, during a macro recording, I go to the start of the last selection I had, then the macro recorder goes where I want. If I then go across to the end of the last selection, then the Macro goes to a specific amount to the right. I do not want that. I want it to go to the end of my last selection.

A specific example.

This is what I have, and is a Word that I select before running the macro:

Code: Select all

WithEvents
BBBlueBefore.jpg
http://imgur.com/CBuqjqP" onclick="window.open(this.href);return false;

This is what I want the macro to give me back:

Code: Select all

[color=blue]WithEvents[/color]
BBBlueAfter.jpg
http://imgur.com/hxWIahh" onclick="window.open(this.href);return false;

_.............

Here is what the Macro recorder gave me, Line 30 is the one not doing what I want. I am guessing that there is a Selection.Charactercount or Selection.EndOf Property which I have not been able to Google or find by experimenting yet. ( Selection.EndOf gives me 2 in this case ??? )

Code: Select all

Sub Makro8()
10    Selection.MoveLeft Unit:=wdCharacter, Count:=1
20    Selection.TypeText Text:="[color=blue]"
30    Selection.MoveRight Unit:=wdCharacter, Count:=10 ' I do not want this to go "10" - I want it to go to the end of my selected word,
40    Selection.TypeText Text:="[/color]"
End Sub
So
Question 1)
Can you help me with the code for this?

Question 2)
Why does the macro recorder not allow me to make a selection? ( Or is a there a way to do that? )
( On a macro recording it seems to work on the last selection )

Thanks
Alan
You do not have the required permissions to view the files attached to this post.
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: VBA Macro to Add Text on End Of Selected Text

Post by HansV »

Re 2)

You cannot select text with the mouse while recording a macro, but you can select text using the keyboard.
Best wishes,
Hans

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Thanks Hans,
That is good to know. I find that weird, but probably just as I am used to Excel where that can be done.

I can see what my macro recording is doing, - simply moving across as I do with the keyboard.
I want the macro to go at line 30 to the end of the last selection.

Actually by “moving along” I am not really selecting? By selecting I mean doing something that highlights a Word.
If I could do that, and then do something that takes me to the end of the Selection directly, rather than “moving along”, then I might get a macro recording to do what I want.

I was thinking a code to do this would be very easy. Possibly things in Word are much different when it comes to Selections.

Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Ahh.. I got it. :smile: But it was not so straight forward.
I can get the character count of the selection through Selection.Characters.Count .._..
_... BUT : - I must do that BEFORE I add my fist bit at line 20, as that seems to reset the selection to ( probably 0, but it gives 1 for it )

So this works:

Code: Select all

 Sub Makro8()
Dim Cnt As Long: Let Cnt = Selection.Characters.Count ' Do this here, and  not after Line 20 , as that seems to reset the selection to ( probably 0, but it gives 1 for it ?? )
10    Selection.MoveLeft Unit:=wdCharacter, Count:=1
20    Selection.TypeText Text:="[color=blue]"
30    Selection.MoveRight Unit:=wdCharacter, Count:=Cnt
40    Selection.TypeText Text:="[/color]"
End Sub
( I wonder if there is a way like in Excel VBA to put the selection in a Variable and work on that, as I guess that would be more efficient, although for a single Word it may be a bit unnecessary, just interesting from a learning point of view )

Anyway got there :smile:
Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
StuartR
Administrator
Posts: 12605
Joined: 16 Jan 2010, 15:49
Location: London, Europe

Re: VBA Macro to Add Text on End Of Selected Text

Post by StuartR »

To use a range instead of a selection you could try...

Code: Select all

Sub Makro8()
    Dim rng As Range
    Set rng = Selection.Range
    rng.InsertBefore "[color=Blue]"
    rng.InsertAfter "[/color]"
    Set rng = Nothing
End Sub
StuartR


User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Hi Stuart
Thanks, that works nicely.
It looks like a more efficient / direct way of doing it.

Thanks
Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
StuartR
Administrator
Posts: 12605
Joined: 16 Jan 2010, 15:49
Location: London, Europe

Re: VBA Macro to Add Text on End Of Selected Text

Post by StuartR »

It is usually much quicker to use Ranges in word than to play with the Selection.
StuartR


User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Thanks Stuart.
I guessed it probably was quicker to do something along those lines.
I know it is in Excel VBA, but I have no Word VBA experience so I was not to sure of the equivalent.
My Excel VBA thinking would have said to copy that Word string to a variable, do the manipulation of adding those bits on and then paste that back out.

But your solution is perfect, does just what I want. I think Set rng = Selection.Range is what I was missing.

I take your word for it that working with ranges is quicker. I have virtually no experience with Word VBA

I note this also works

Code: Select all

Sub Makro9()   '    https://eileenslounge.com/viewtopic.php?f=26&t=25185&p=195286#p195289
  Selection.InsertBefore "[color=Blue]"
  Selection.InsertAfter "[/color]"
End Sub
But I note Selection here does not seem to be a Range in Word. In Excel this
Set rng = Selection
Works.
But it errors in Word. That is one thing that threw me off

This I just tried , it might finally satisfy my like of “doing things internally”

Code: Select all

 Sub Makro10()   '    https://eileenslounge.com/viewtopic.php?f=26&t=25185#p195286
Dim rng As Range
 Set rng = Selection.Range
Dim Txt As String
 Let Txt = rng.Text
 Let Txt = "[color=Blue]" & Txt & "[/color]"
 Let rng.Text = Txt
Set rng = Nothing
End Sub
Thanks again
Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
Jay Freedman
Microsoft MVP
Posts: 1318
Joined: 24 May 2013, 15:33
Location: Warminster, PA

Re: VBA Macro to Add Text on End Of Selected Text

Post by Jay Freedman »

While that will work, it uses up a lot more code than necessary. This version is exactly equivalent:

Code: Select all

Sub Makro11()
Dim rng As Range
Set rng = Selection.Range
rng.Text = "[color=Blue]" & rng.Text & "[/color]"
Set rng = Nothing  ' optional
End Sub
In the line that includes "", the expression rng.Text on the right side is the original text, and the same expression on the left side is the modified text. There's no need for a separate String value (Txt).

Also, the keyword Let is optional in ordinary assignment statements. It's necessary only when you're defining Get and Let functions. In contrast, the Set keyword is required whenever you assign to an object (a variable that has properties and methods, of which a Range variable is one).

Finally, in a simple macro like this, you can omit the Set rng = Nothing statement and just let VBA destroy the object when it goes out of scope (when the macro ends).

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: VBA Macro to Add Text on End Of Selected Text

Post by HansV »

If you wish, you can omit the variable rng too, and work directly with the Text property of the Selection:

Code: Select all

Sub Makro11()
    Selection.Text = "[color=Blue]" & Selection.Text & "[/color]"
End Sub
or

Code: Select all

Sub Makro11()
    With Selection
        .Text = "[color=Blue]" & .Text & "[/color]"
    End With
End Sub
Best wishes,
Hans

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Hi Hans, Hi Jay Freedman,
Thanks for the extra input :)

My final version I ended up using_....

Code: Select all

Sub Makro9()   '   
  Selection.InsertBefore "[color=Blue]"
  Selection.InsertAfter "[/color]"
End Sub
_..... was not too far off, but I think I can follow your codes.

For doing stuff on a single word or short sentences then this_..

Code: Select all

Selection.Text = "[color=Blue]" & Selection.Text & "[/color]"
_.. looks the thing to go for


The little bit of computer knowledge that I have is in Excel VBA. My work there is often to do with manipulating big files and I have got into the habit of often putting things into Arrays and working “internally” before then pasting back Big Arrays out in one or a few steps

The analogy here with my VBA work would be if I was looking manually and changing a Cell or two, in which case a similar code would work there also.
I probably have a bit of a conceptual problem of what a Selection is in WORD VBA. ( or a Range come to think of it ). In VBA Selection is a Range Object.

For the little I use Word VBA I probably don’t need to worry too much – I have enough problems trying to understand some Excel VBA Logic,.. Lol... Although stretching the mind is never a bad thing. :)

_......
@ Jay Freedman
Thanks for the other info.

When I post in Forums it is sometimes a learning thing , mostly here at Eileen’s Lounge I ask questions, but on other forums, I mostly answer, ( But in doing so also learn a lot ) … and I have a bit of a ( bad ! ) reputation of including lots of extra steps, ‘Comments etc.. A select minority of people love it, most hate it. :(

Codes that I use just for myself are often a lot different. If I have time I do 2 code versions,
_ - a full code that has extra lines variable and a book load of ‘Comments
_ - a much more condensed version – I have a few awesome “one liner codes” – that is one thing that I find an interesting aspect of Object Orientated Programming which still occasionally seems a wiered concept to my Old Fortran, Pascal, Basic brain
_..

I understand what you are saying about the Let, Set stuff.. but I often forget the differences, and so I always include( in my full code versions ) the Let to remind me of things I can Let , things I should Set , and things I should not do either. And also until recently my last Computer experience was about 25 – 30 years ago, so I got used to Let in Basic,
_- Along with Rem and code lines it has become another Trademark of mine to love or hate.

The …”… … in a simple macro like this, you can omit the Set rng = Nothing statement and just let VBA destroy the object when it goes out of scope (when the macro ends). ….”… is a good point to know about in WORD VBA, so thanks for that.
This thinking is something that I do “subscribe to” mostly, at least in VBA. – A lot of the ( younger ) experts have said something similar to me in VBA.
As it is not needed it is better not to use it so as not to mask the cases ( exceptions apparently in VBA do exists ) when that should be done. Ironically I got that habit from much more Senior Experts who claimed or thought it was necessary. Apparently, some strange sort of leakage, Thrashing , Uncleared memory or the such problems used to occur once with these things.
But I actually have some headaches in a similar area currently, and one of the few things I can say is that doing a Set = Nothing has never made any difference. So I am with you on that one

Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: VBA Macro to Add Text on End Of Selected Text

Post by HansV »

Hi Alan,

Both in Excel VBA and in Word VBA, the Selection object can be different things, it isn't always a range.

For example in Excel, it usually is a Range, but if you have selected a chart, it is a ChartObject, and if you have selected a picture or a rectangle (for example), it is a Shape.

In Word, it is often a text range, but it could also be a shape.
Word VBA handles the Selection object a bit differently than Excel, though: in Excel VBA, TypeName(Selection) will return "Range" or "Rectangle" etc., depending on the actual contents of the selection, but in Word VBA, it will always return "Selection". But, as you see in the discussion above, you can use Selection.Text as well as Selection.Range.Text if the selection is a text range.
Best wishes,
Hans

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: VBA Macro to Add Text on End Of Selected Text

Post by Doc.AElstein »

Hi Hans

Thanks for that – I think with VBA I am a bit narrow minded as well – I have never been near a chart and the “pretty” stuff that end up as shape are not on play list.

There I was getting quite happy and good ( I thought ) in my understanding of Range Objects.

I think ( and I bet a lot of others hope ) I will not be getting into Chart objects.. or Shapes.. God my posts would then be worth millions as new form of abstract Art

Alan
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also