VBA中如何为Class对象分配Shape?赋值时遇对象未设置错误
问题解决:对象变量或With块未设置错误
错误的核心原因是对象类型的属性赋值必须使用Property Set,而非Property Let。Property Let仅适用于值类型(如字符串、整数),而Shape是对象,需要用Property Set来定义赋值接口。
修正后的CShapes类代码
Option Explicit Private m_Shape As Shape Public Property Get Shape() As Shape Set Shape = m_Shape End Property Public Property Set Shape(ByVal pShape As Shape) ' 将Let替换为Set Set m_Shape = pShape End Property
原方法代码无需修改
Sub CustomShapes() Dim star As New CShapes ' 声明并实例化CShapes对象 Dim shp1 As Shape Set shp1 = ActiveSheet.Shapes.AddShape(msoShape16pointStar, _ ActiveCell.Left, ActiveCell.Top, 80, 27) Set star.Shape = shp1 ' 为CShapes对象的Shape属性赋值 End Sub
修改后执行Set star.Shape = shp1就不会再触发"对象变量或With块未设置"的错误,因为类中已通过Property Set正确实现了对象类型属性的赋值逻辑。
内容的提问来源于stack exchange,提问作者Megan
相关产品推荐
相关产品推荐

