使用 AddPolyline 和 Excel 中的顶点列表在 AutoCAD VBA 中创建闭合形状

问题描述 投票:0回答:1
Sub CreateClosedShape()
    Dim myDwg As AcadDocument
    Set myDwg = AutoCAD.Application.ActiveDocument
    
    ' Assuming your Excel data is in Sheet1, starting from cell A1
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    ' Assuming your data consists of X and Y coordinates in columns A and B
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' Check if there are enough points to create a closed shape
    If lastRow < 2 Then
        MsgBox "Insufficient data to create a closed shape.", vbExclamation
        Exit Sub
    End If
    
    ' Get the vertices as a list
    Dim verticesList As Variant
    ReDim verticesList(1 To lastRow, 1 To 2)
    
    Dim i As Long
    For i = 1 To lastRow
        verticesList(i, 1) = ws.Cells(i, 1).Value
        verticesList(i, 2) = ws.Cells(i, 2).Value
    Next i
    
    ' Create a polyline to represent the closed shape
    Dim polylineObj As AcadPolyline
    Set polylineObj = myDwg.ModelSpace.AddPolyline(verticesList)
    
    ' Close the polyline by adding a closing segment
    Dim firstX As Double
    Dim firstY As Double
    firstX = ws.Cells(1, 1).Value
    firstY = ws.Cells(1, 2).Value
    
    ' Add the first vertex again to close the polyline
    polylineObj.AddVertex firstX, firstY
    
    MsgBox "Closed shape created successfully!", vbInformation
End Sub

我是vba新手,无法在autocad中制作cad对象。我收到此行的无效对象错误(Set polylineObj = myDwg.ModelSpace.AddPolyline(verticesList))。看起来不错,但不知道为什么会这样。

vba arguments runtime-error autocad invalid-argument
1个回答
0
投票

AutoCAD 的

AddPolyline
方法需要一个从零开始的双精度数组,其中第一个元素是 X,第二个元素是 Y,第三个元素是 Z,第四个元素是 X,第五个元素是 Y,第六个元素是 Z等等。但是,您应该考虑使用
AddLightWeightPolyline
而不是
AddPolyline
。它只需要 X、Y 对,而不需要 X、Y、Z 三元组。另外,
AddPolyline
仅用于向后兼容。

以下代码实现了

AddLightWeightPolyline
的这个想法:

Dim verticesList() As Double
ReDim verticesList(0 To lastRow * 2 - 1)
   
Dim i As Long
Dim j As Long
j = -1
   
For i = 1 To lastRow
   j = j + 1
   verticesList(j) = ws.Cells(i, 1).Value
   j = j + 1
   verticesList(j) = ws.Cells(i, 2).Value
Next i

您不需要手动关闭折线。你可以这样做:

polylineObj.Closed = True

这里是AutoCAD 文档的链接。

© www.soinside.com 2019 - 2024. All rights reserved.