Excel Crashing Without Error When Form.Controls.Add is Called
Have you encountered a mysterious Excel crash without any error message when using the form.Controls.Add
method in VBA? You're not alone. Many users have reported this issue, and unfortunately, there's no clear explanation or permanent solution yet.
Potential Cause and a Workaround:
Some users have found that the crash occurs when adding a MSForms.Frame
object to a container within a UserForm. A workaround is to add the frame contents (image and labels) directly to the container and control their positioning using a custom Sub
method.
Replicating the Issue:
- Create a new UserForm (UserForm1).
- Add a Frame (FrameA).
- In the UserForm's code module, add this code:
Private Sub UserForm_Activate()
Set b = FrameA.Controls.Add("Forms.Frame.1", "FrameB")
End Sub - Add a module (Module1) with this code:
Sub showUserForm1()
UserForm1.Show
End Sub - Run
showUserForm1
.
With this setup, Excel will crash when you run showUserForm1
. However, if you add a second Frame (FrameC) and modify the code in UserForm_Activate
to add FrameD within FrameC, the crash will occur when adding FrameD.
- Avoid using frames and place controls directly in the UserForm.
- Ensure that the frame you're adding another frame to is at the top in design mode.
- Try creating all frames at runtime, starting with the innermost frame.
- Recreating and deleting the referenced control in the UserForm.
- Placing a frame in the view before running the code to add multiple frames.
While these methods may work for some users, there's no guarantee that they will resolve the issue for everyone. Further investigation is needed to determine the root cause of the crash and develop a permanent solution.