加载图片到VBA用户窗体时出现Runtime Error 91错误求助
Fixing Runtime Error 91 in Your VBA Image Loading Code
Hey there! Let's tackle that Runtime Error 91 you're hitting. This error usually pops up when you're trying to work with an object reference that's either Nothing or not set up the way you expect. Let's break down what's off in your code and how to fix it.
What's Causing the Error?
Your problematic line:
Set img = ThisWorkbook.VBProject.VBComponents("UserForm10").Designer.Controls("Image3").Picture
has two critical issues:
.Pictureis a property, not an object you can assign withSet— trying to set an object variable to it will fail immediately.- When loading an image at runtime, you don't need to dig into the
VBProjectdesigner. You can directly reference the form's image control using a form instance, which is the standard runtime approach.
Also, your check for the user canceling the file picker is slightly off: GetOpenFilename returns a Variant (a boolean False when canceled), not a string, so comparing it to "False" won't work correctly.
Corrected Code
Here's the fixed version of your code that should run without errors:
Dim Pict As Variant ' Changed to Variant to handle boolean cancel value Dim ImgFileFormat As String Dim targetForm As UserForm10 ' Direct reference to your user form ImgFileFormat = _ "Image Files (*.bmp;*.gif;*.tif;*.jpg),*.bmp;*.gif;*.tif;*.jpg" ' Fixed typo in file extensions GetPict: Pict = Application.GetOpenFilename(ImgFileFormat) If Pict = False Then Exit Sub ' Correct comparison for the Variant return value ' Create an instance of your user form Set targetForm = New UserForm10 ' Load and configure the image directly in the control With targetForm.Image3 .Picture = LoadPicture(Pict) .PictureSizeMode = fmPictureSizeModeStretch End With ' Show the form if you want to display the loaded image targetForm.Show
Key Fixes Explained
- Switched
PicttoVariant: This lets you properly detect when the user cancels the file picker (sinceGetOpenFilenamereturns a booleanFalsein that case). - Direct form instance: Instead of messing with the
VBProjectdesigner, we create an instance ofUserForm10and access itsImage3control directly — this is the standard, reliable way to interact with forms at runtime. - Proper picture assignment: We set the
.Pictureproperty directly usingLoadPicture(Pict)instead of trying to assign the property to an object variable first. - Fixed file extension typo: Your original format string had
*bmpinstead of*.bmp, which ensures the file picker filters image files correctly.
Quick Additional Checks
If you still run into issues, double-check:
UserForm10actually exists in your workbook's VBA project.Image3is a valid Image control onUserForm10(verify the name in the control's properties window).- Your macro security settings allow access to the VBA project object model if you ever need to use
VBProjectin other code.
内容的提问来源于stack exchange,提问作者Adil
相关产品推荐
相关产品推荐

