Creating a Closed Shape in AutoCAD VBA Using AddPolyline with Vertex List from Excel

60 views Asked by At
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

i am new to vba to make cad objects in autocad. I am getting error of invalid object for this line (Set polylineObj = myDwg.ModelSpace.AddPolyline(verticesList)). its seems ok but dont know why it giving that.

1

There are 1 answers

0
Brian M Stafford On

AutoCAD's AddPolyline method requires a zero-based array of doubles where the first element is X, the second element is Y, the third element is Z, the fourth element is X, the fifth element is Y, the sixth element is Z and so on. However, you should consider using AddLightWeightPolyline instead of AddPolyline. It only requires X, Y pairs instead of X, Y, Z triplets. Also, AddPolyline is for backwards-compatibility only.

The following code implements this idea for 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

You don't need to manually close the polyline. You can do this instead:

polylineObj.Closed = True