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.
AutoCAD's
AddPolylinemethod 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,AddPolylineis for backwards-compatibility only.The following code implements this idea for
AddLightWeightPolyline:You don't need to manually close the polyline. You can do this instead: