Excel 从主模块调用userform函数并填充imageBox

Excel 从主模块调用userform函数并填充imageBox,excel,vba,userform,Excel,Vba,Userform,我试图让一个userform从我的主模块调用这个函数,并让它将imagebox设置为形状。。。当这个函数在userform代码中时,它运行得很好,但是我试图避免为我的所有userforms复制这个代码。。。。当我将此函数放入userform时,“Me.”和“as Object”被删除在例程中添加一个参数: Public Function LoadImage() As Object For Each pics In sheetImages.Shapes If (CStr(pics.N

我试图让一个userform从我的主模块调用这个函数,并让它将imagebox设置为形状。。。当这个函数在userform代码中时,它运行得很好,但是我试图避免为我的所有userforms复制这个代码。。。。当我将此函数放入userform时,“Me.”和“as Object”被删除

在例程中添加一个参数:

Public Function LoadImage() As Object

  For Each pics In sheetImages.Shapes
    If (CStr(pics.Name) = CStr(currpartImage)) Then
      Me.ImagePreview.Picture =PictureFromShape(sheetImages.Shapes(currImage))
      Me.ImagePreview.PictureSizeMode = 3
      currImageRow = sheetImages.Shapes(currpartImage).TopLeftCell.row + 1
    End If
  Next
End Function
从您的表格中调用:

Public Sub LoadImage(imageControl as Object) As Object
  For Each pics In sheetImages.Shapes
    If (CStr(pics.Name) = CStr(currpartImage)) Then
      imageControl .Picture =PictureFromShape(sheetImages.Shapes(currImage))
      imageControl .PictureSizeMode = 3
      currImageRow = sheetImages.Shapes(currpartImage).TopLeftCell.row + 1
    End If
  Next
End Sub

您还需要传递在
LoadImage
中引用但不在userform范围之外的任何其他项。

Me
仅在对象模块(userform/sheet/class)内有效,并引用对象实例本身(在您的情况下为userform)。如果您想从常规模块中的代码中访问某些特定项(控件等),则应将其作为参数添加到函数中,并从调用代码中传递该项。另外,如果代码是Sub而不是函数,则更有意义,因为它不会返回值。如何访问图像控件?它是否类似于Userform.Controls(ImagePreview.Picture=。。。。
LoadImage Me.ImagePreview