vba - How to select the contents of a textbox once it is activated? -


i have simple userform, have textbox1 , textbox2. enter text in both of them. assume focus on (the cursor in) textbox2. when click on textbox1, want whole text in control highlighted (selected). use code:

private sub textbox1_enter()     textbox1         .setfocus         .selstart = 0         .sellength = len(.text)     end     msgbox "enter event fired" end sub 

there msgbox @ end loaded, means event works. however, text not highlighted. how fix this?

i use enter event , don't want use mousedown event, because need code work when textbox1 activated programatically, feel enter event best choice, it's fired in both cases! drawback of mousedown event is: when click second time on textbox1, not expect whole text highlighted anymore, because focus set on first click , not changed after clicked on same control second time; in case cursor act (not keep text marked).

update
when click once on textbox1, expect have result: enter image description here
if clicked again, highlight removed , cursor placed in place clicked.

can't more simple guess...

private sub textbox1_mousedown(byval button integer, byval shift integer, _ byval x single, byval y single)     textbox1         .selstart = 0         .sellength = len(.text)     end end sub 

whether click on textbox or tab it, want. deselect text, use arrow keys.

explanation

if debug code see though have said .setfocus, focus not on textbox. .setfocus doesn't work in textbox1_enter() , need have focus rest of code work. , hence alternative...

alternative

you may version :) overcomes limitation of using mouse in textbox

dim boolenter boolean  private sub textbox1_enter()     boolenter = true end sub  private sub textbox1_mousedown(byval button integer, byval shift integer, _ byval x single, byval y single)     if boolenter = true         textbox1             .selstart = 0             .sellength = len(.text)         end         boolenter = false     end if end sub 

Comments