Reputation: 145
I have several forms, and there are several lines of code used to call and place each one. Instead of replicating these lines of code for each form, I want to use a subroutine simply to load and place a form. This code works:
Sub LoadForm_BulletBeginningEmphasis()
Load formBulletBeginningEmphasis
formBulletBeginningEmphasis.Show
formBulletBeginningEmphasis.StartUpPosition = 0
formBulletBeginningEmphasis.Left = Application.Left + (0.5 * Application.Width) - (0.5 * formBulletBeginningEmphasis.Width)
formBulletBeginningEmphasis.Top = Application.Top + (0.5 * Application.Height) - (0.5 * formBulletBeginningEmphasis.Height)
End Sub
What I want, though, is for this code to work, instead:
Public Sub LoadAndShowForms(ByVal formName As Object)
Load formName
formName.Show
formName.StartUpPosition = 0
formName.Left = Application.Left + (0.5 * Application.Width) - (0.5 * formName.Width)
formName.Top = Application.Top + (0.5 * Application.Height) - (0.5 * formName.Height)
End Sub
Sub LoadForm_BulletBeginningEmphasis()
Call LoadAndShowForms(formBulletBeginningEmphasis)
End Sub
The problem is that when I execute the second set of code lines, they work and the form works, but when the form disappears, VBA throws an error:
What's going on here? Why is the second version working but throwing an error?
Upvotes: 0
Views: 150
Reputation: 25673
Put the Show
method after the positioning commands.
If you think about it, this makes sense as code execution pauses when a modal UserForm is shown. Code that executes after Show
logically shouldn't have any effect.
Depending on how the UserForm "disappears", the error will show up. If there's code "behind" the UserForm that unloads it then the "callee" (the UserForm) is no longer available. If the code only hides the UserForm, then an error may not occur (because the object is still loaded in memory).
It also makes a difference when calling the from another procedure: In the question's first code sample it's likely that the procedure is simply ending silently, even though it doesn't execute the positioning of the form. In the second code sample, execution has to return control to the calling procedure, but it can't because the procedure it called can't finish correctly.
Upvotes: 1
Reputation: 411
I believe your problem is that you are passing the form ByVal and it should be ByRef. Public Sub LoadAndShowForms(ByRef formName as Object)
. I would also change Object
to UserForm
. Your sub's signature would become Public Sub LoadAndShowForms(ByRef formName as UserForm)
Upvotes: 0