关闭重开Excel后,Connector与Button连接断开问题求助
问题:Excel VBA生成的按钮连接线关闭重开后失效
我用VBA生成两个表单按钮,并用连接线(Connector)连接它们,但关闭再打开Excel文件后,连接线不再和按钮保持连接。换成普通矩形时没有这个问题,怀疑是通过ShapeRange.Item(1)连接按钮的方式有问题,但不知道其他可行方法。
原代码如下:
Sub CreateStuff() Dim btn(1 To 2) As Button Set btn(1) = ThisWorkbook.Worksheets(1).Buttons.Add(50, 50, 100, 200) Set btn(2) = ThisWorkbook.Worksheets(1).Buttons.Add(300, 300, 150, 150) Dim newConnector As Object Set newConnector = ActiveSheet.Shapes.AddConnector(msoConnectorStraight, 0, 0, 100, 100) With newConnector .ConnectorFormat.BeginConnect btn(1).ShapeRange.Item(1), 1 .ConnectorFormat.EndConnect btn(2).ShapeRange.Item(1), 3 End With End Sub Sub TestConnection() With ThisWorkbook.Worksheets(1).Shapes Dim i As Integer For i = 1 To .Count If .Item(i).Connector Then If .Item(i).ConnectorFormat.BeginConnected And .Item(i).ConnectorFormat.EndConnected Then MsgBox "Connection present" Else MsgBox "No Connection" End If End If Next i End With End Sub
原因分析
Excel的表单控件按钮(Button对象)本质是嵌入在Shape容器中的控件,通过Button.ShapeRange.Item(1)获取的是这个容器的临时引用,但保存并重新打开文件后,容器与按钮的绑定关系会丢失,导致连接线无法找到对应的连接目标。而普通矩形本身就是Shape对象,不存在层级嵌套问题,所以连接能稳定保持。
解决方案
直接操作Shape对象添加表单按钮,跳过Button对象的中间层,用Shape对象直接与连接线建立连接,这样保存后引用关系不会丢失。
修改后的代码:
Sub CreateStuff_Fixed() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets(1) ' 直接用Shapes添加表单按钮,获取Shape对象 Dim btnShape(1 To 2) As Shape Set btnShape(1) = ws.Shapes.AddFormControl(xlButtonControl, 50, 50, 100, 200) btnShape(1).Name = "Button1" ' 给按钮命名,方便后续识别维护 Set btnShape(2) = ws.Shapes.AddFormControl(xlButtonControl, 300, 300, 150, 150) btnShape(2).Name = "Button2" ' 添加连接线并直接连接Shape对象 Dim newConnector As Shape Set newConnector = ws.Shapes.AddConnector(msoConnectorStraight, 0, 0, 100, 100) With newConnector.ConnectorFormat .BeginConnect ConnectedShape:=btnShape(1), ConnectionSite:=1 .EndConnect ConnectedShape:=btnShape(2), ConnectionSite:=3 End With ' 自动调整连接线到最优位置 newConnector.RerouteConnections End Sub Sub TestConnection() With ThisWorkbook.Worksheets(1).Shapes Dim i As Integer For i = 1 To .Count If .Item(i).Connector Then If .Item(i).ConnectorFormat.BeginConnected And .Item(i).ConnectorFormat.EndConnected Then MsgBox "连接正常" Else MsgBox "连接已丢失" End If End If Next i End With End Sub
关键改动说明
- 用
Shapes.AddFormControl替代Buttons.Add,直接获取Shape对象,避免通过Button的ShapeRange间接引用 - 给按钮Shape命名,方便后续定位和维护(可选但推荐)
- 调用
RerouteConnections确保连接线自动适配按钮位置 - 直接使用Shape对象作为
BeginConnect和EndConnect的ConnectedShape参数,建立稳定的连接关系
内容的提问来源于stack exchange,提问作者Matthias Klupsch
相关产品推荐
相关产品推荐

