AutoCAD Macro to Export 2D Polyline Coordinates to Excel

Pick a polyline and this VBA macro writes the X and Y of every vertex, plus the polyline’s length and number of vertices, to a CSV file for Excel. Handy for road centrelines, plot boundaries and setting-out.

ExportsX, Y of each vertex, length, vertex count
Works onLWPOLYLINE (normal 2D polylines)
Outputpolyline.csv, next to the drawing

The macro

Sub ExportPolyline()
    Dim ent As AcadEntity, pick As Variant, c As Variant
    Dim i As Long, f As String
    ThisDrawing.Utility.GetEntity ent, pick, "Select a polyline: "
    If Not TypeOf ent Is AcadLWPolyline Then
        MsgBox "That isn't a 2D polyline.", , "XL n CAD": Exit Sub
    End If
    c = ent.Coordinates
    f = ThisDrawing.Path & "\polyline.csv"
    Open f For Output As #1
    Print #1, "X,Y"
    For i = 0 To UBound(c) Step 2
        Print #1, Trim(Str(c(i))) & "," & Trim(Str(c(i + 1)))
    Next i
    Print #1, "Length," & Trim(Str(ent.Length))
    Print #1, "Vertices," & (UBound(c) + 1) / 2
    Close #1
    MsgBox "Saved to " & f, , "XL n CAD"
End Sub

How to run the macro

  1. AutoCAD 2010 and later need the free VBA Enabler (VBA module) from Autodesk for your version. AutoCAD LT doesn’t support VBA.
  2. Save the drawing first: the file is written to the drawing’s folder.
  3. Type VBAIDE (or press Alt + F11), choose Insert → Module, and paste the code.
  4. Close the editor, type VBARUN (or Alt + F8), pick the macro and click Run.
  5. Open the CSV file in Excel.

Numbers are written with Str(), which always uses a dot as the decimal separator, so the CSV opens correctly in Excel whatever your Windows region settings.

What changed from the original code

Original code Problem Fixed
No Sub line The code won’t run Added
Curly quotes “ ” The code won’t run Straight quotes
Selecting a line or 3D polyline Crashed with Type mismatch Checks the type and shows a message
Dim i As Integer Overflows on very long polylines Long

Things to know

  • A 2D polyline has one elevation for all vertices; read it with ent.Elevation if you need Z.
  • Arcs in the polyline are exported as their end points only.
  • If the polyline was drawn in a rotated UCS, coordinates are in its own plane; draw or check it in the World UCS.
  • For 3D polylines, use the 3D polyline macro.

Related