Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Lostfocus not the same as click?

Status
Not open for further replies.

simon1tan

MIS
Aug 3, 2011
7
US
I've got some VBA code to copy and paste in word. Using a button and the click event, this code works wonderfully. Using a textbox and the lostfocus event, the code errors out at Selection.HomeKey saying "Method 'HomeKey' of object 'Selection' failed". When I comment out Selection.Homekey, the .Execute fails with "The command is not available". I'm sure this is simple, but this is my first time with Word VBA. What am I missing? Thanks for the advice.

Me.Activate
Selection.HomeKey
With Selection.Find
.Forward = True
.Wrap = wdFindStop
.Text = "#simon#"
.Execute
End With

 
In debugging it occurs that the code executes twice, the Selection.HomeKey calls the event again (see the stack when tracing the code execution). You can put 'On Error' statement to avoid second run, but the effect will be probably different from what you expect:
Code:
Private Sub TextBox1_LostFocus()
On Error GoTo ErrH
Me.Activate
Selection.HomeKey
With Selection.Find
    .Forward = True
    .Wrap = wdFindStop
    .Text = "#simon#"
    .Execute
End With
ErrH:
End Sub{/code]

combo
 
What are you trying to achieve?

While in the event code, the Selection is in a curious limbo but, more importantly, any attempt to do anything outside the textbox will trigger the loss of focus event and you will - most likely - loop recursively until you run out of memory.


Enjoy,
Tony

------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

I'm working (slowly) on my own website
 
I have a textbox. I want it to trigger on lostfocus, copy text from another word document, paste into a field or replace a designated text pattern in current document. I have it working using a command button click but textbox lostfocus does not work. And you are right, it seems like a focus thing but I have not been able how to refocus it on the document text. That is what the Selection.Homekey was supposed to do. :). Any ideas?

Here is the whole thing using command button:
Me.Activate
Selection.HomeKey
With Selection.Find
.Forward = True
.Wrap = wdFindStop
.Text = "#simon#"
.Execute
End With
ID = TextBox1.Value
sFile = "C:\temp\" & ID & ".doc"
Set sourcedoc = Application.Documents.Open(sFile)
sourcedoc.Range.Copy
Me.Activate
Selection.Paste
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top