Visual Basic - how to force event to fire

折月煮酒 提交于 2019-12-13 01:57:15

问题


I'm new to VB (using VBA, actually) and I would like to force an event to fire. Specifically, I am updating the value in a textbox and I would like to call that textbox's AfterUpdate() event.

Private Sub cmdCreateInvoice_Click()
  Me.txtInvDate = '11/01/10'
  Me.txtInvDate.AfterUpdate
End Sub

During run time, I get an error that says "Compile Error: Invalid Use of Property". If I try something similar, but with the click event (ex: cmdCreateInvoice.Click), which does NOT have a property that shares the name, I get an error that says "Compile Error: Method or Data member not found".
I know there must be a way to fire one event from another. But what is the proper syntax? Thanks!


回答1:


AFAIK, there is no way to "fire an event manually" in VB(A). What you can do is call the event handler manually, and for this, rdkleine has given you the answer already:

Call txtInvDate_AfterUpdate()

This will have exactly the same effect as if the event had fired (though it does not give you the whole chain of events that may also fire along with it--unless you Call their handlers as well).

IgorM has another valid point, in comments on his answer--it's "cleaner" to write a different Sub to do the work you want done, then call it from both the event handler & wherever you're trying to do it now (button click?). So:

Private Sub txtInvDate_AfterUpdate()
    DoWhatever
End Sub

Private Sub button_Click()
    DoWhatever
End Sub

Private Sub DoWhatever
    'your desired effect
End Sub

You could even make DoWhatever a Public Sub in a Module.

Edit

And no, in VB(A) it doesn't matter what order you define your Sub (or Function) routines.




回答2:


Call

txtInvDate_AfterUpdate()




回答3:


Try to use something like this:

Private Sub TextBox1_LostFocus()
  TextBox1.Value = "5"
End Sub

Use LostFocus event if you change value manually.

Or you can use another way:

Private Sub CommandButton1_Click()
   TextBox1.Value = "new value"
End Sub

Private Sub TextBox1_Change()
   MsgBox TextBox1.Value
End Sub

Try to use Change event.




回答4:


Some code apparently will (regretfully) force events to fire:

    Me.Dirty = False

forces BeforeUpdate and AfterUpdate to fire, as I understand it. There are probably more cases too. Any secret hooks which attach to your code in that manner reflect bad design in my view and will inevitably lead to inadvertant & frustrating loops being created.



来源:https://stackoverflow.com/questions/4500335/visual-basic-how-to-force-event-to-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!