سؤال

So, If i have this function in a userform:

function myFunc() as String
    Me.Show vbModal
    stringVar = "Second"
end function

and I have the click event of the lone command button on said userform:

Private Sub cmdbutton_Click()
    Unload Me
    stringVar = "First"                                                  
End Sub

My question is, when I call that function ("MyFunc") from somewhere, will the click event of the button ("cmdButton") continue processing before the function is allowed to continue, or is it basically a coin toss? this stringVar variable is a private variable of the userform. it gets set in the click event of that button, but I want to use it in the function, after the click has happened. (there will be other components on the form, calculations, etc...)

so is there any risk that the function will continue processing before the click event finishes? If the function continues before the click event, then the variable wont be set properly

هل كانت مفيدة؟

المحلول

My question is, when I call that function ("MyFunc") from somewhere, will the click event of the button ("cmdButton") continue processing before the function is allowed to continue, or is it basically a coin toss?

Let me explain it with an image followed by a description

enter image description here

  1. When you run the function, the first line is executed. Now since the form is shown as modal, the next line which is stringVar = "Second" will not run till the time the userform is unloaded.
  2. The next line which will execute in the above scenario is Unload Me. However, it doesn't mean that any code after that will not run. Unload Me is not like Exit Do or Exit For. It just unloads the object and in no way stop further execution of the script/code.
  3. So obviously the next line which is executed is stringVar = "First" and it reaches End Sub
  4. This is the time the control has been returned to the function and it continues to execute the next line which is stringVar = "Second"

Hope this makes sense. If it doesn't then please feel free to ask whatever doubts that you have.

You can also see the execution of the code by stepping through it using F8.

For further reading: Debugging VBA Code

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top