You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Excel VBA代码:创建避开中间形状的形状连接线

Excel VBA:创建绕行指定形状的连接线

要让形状A和C之间的连接线避开中间的形状B,仅依赖RerouteConnections无法自动识别中间障碍,需要手动定义连接线的路径顶点。以下是修改后的代码:

Public Function func_CreateConnectors(ByVal strSheetName As String, _
                                    ByVal strShape1Name As String, _
                                    ByVal strShape2Name As String, _
                                    ByVal strAvoidShapeName As String, _
                                    ByVal strConnectorName As String, _
                                    ByVal dbConnectorWeight As Double)
    Dim sStart As Shape, sEnd As Shape, sAvoid As Shape, connector As Shape
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(strSheetName)
    
    ' 获取三个形状的引用
    Set sStart = ws.Shapes(strShape1Name)
    Set sEnd = ws.Shapes(strShape2Name)
    Set sAvoid = ws.Shapes(strAvoidShapeName)
    
    ' 创建曲线连接线(初始坐标不影响,后续会调整)
    Set connector = ws.Shapes.AddConnector(msoConnectorCurve, 1, 1, 1, 1)
    
    With connector
        ' 绑定起始和结束形状
        .ConnectorFormat.BeginConnect sStart, 2
        .ConnectorFormat.EndConnect sEnd, 2
        
        ' 设置连接线样式
        .Line.Weight = dbConnectorWeight
        .Name = strConnectorName
        .Line.ForeColor.RGB = RGB(0, 255, 255)
        
        ' 计算绕行路径的顶点(示例:从形状B的上方绕行)
        Dim detourX As Double, detourY As Double
        detourX = (sStart.Left + sEnd.Left) / 2 ' 水平居中于A和C
        detourY = Application.WorksheetFunction.Min(sStart.Top, sEnd.Top, sAvoid.Top) - 50 ' 向上偏移避开B
        
        ' 重置连接线节点,添加绕行路径
        .Nodes.Delete 1, .Nodes.Count ' 清除默认节点
        ' 添加起始节点(绑定到A的中心附近)
        .Nodes.Add 1, msoSegmentCurve, msoEditingAuto, sStart.Left + sStart.Width / 2, sStart.Top + sStart.Height / 2
        ' 添加绕行节点
        .Nodes.Add 2, msoSegmentCurve, msoEditingAuto, detourX, detourY
        ' 添加结束节点(绑定到C的中心附近)
        .Nodes.Add 3, msoSegmentCurve, msoEditingAuto, sEnd.Left + sEnd.Width / 2, sEnd.Top + sEnd.Height / 2
        
        ' 重新绑定确保连接线附着在形状上
        .ConnectorFormat.BeginConnect sStart, 2
        .ConnectorFormat.EndConnect sEnd, 2
    End With
End Function

使用说明:

  • 新增参数strAvoidShapeName,传入需要绕行的形状名称(即形状B)
  • 示例中是从B的上方绕行,若需要其他方向,修改detourX或detourY的计算:
    • 下方绕行:detourY = Application.WorksheetFunction.Max(sStart.Top + sStart.Height, sEnd.Top + sEnd.Height, sAvoid.Top + sAvoid.Height) + 50
    • 左侧绕行:detourX = Application.WorksheetFunction.Min(sStart.Left, sEnd.Left, sAvoid.Left) - 50
    • 右侧绕行:detourX = Application.WorksheetFunction.Max(sStart.Left + sStart.Width, sEnd.Left + sEnd.Width, sAvoid.Left + sAvoid.Width) + 50

调用示例:

' 在Sheet1中创建ShapeA到ShapeC的连接线,绕行ShapeB,线宽2磅
func_CreateConnectors "Sheet1", "ShapeA", "ShapeC", "ShapeB", "AC_Connector", 2

内容的提问来源于stack exchange,提问作者tink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 14:52:21