Pick a 3D polyline and this VBA macro writes the X, Y and Z of every vertex, plus the length and vertex count, to a CSV file. Useful for profiles, contours and road alignments with levels.
ExportsX, Y, Z of each vertex, 3D length, vertex count
Works on3DPOLY objects
Output3dpolyline.csv, next to the drawing
The macro
Sub Export3DPolyline()
Dim ent As AcadEntity, pick As Variant, c As Variant
Dim i As Long, f As String
ThisDrawing.Utility.GetEntity ent, pick, "Select a 3D polyline: "
If Not TypeOf ent Is Acad3DPolyline Then
MsgBox "That isn't a 3D polyline.", , "XL n CAD": Exit Sub
End If
c = ent.Coordinates
f = ThisDrawing.Path & "\3dpolyline.csv"
Open f For Output As #1
Print #1, "X,Y,Z"
For i = 0 To UBound(c) Step 3
Print #1, Trim(Str(c(i))) & "," & Trim(Str(c(i + 1))) & "," & Trim(Str(c(i + 2)))
Next i
Print #1, "Length," & Trim(Str(ent.Length))
Print #1, "Vertices," & (UBound(c) + 1) / 3
Close #1
MsgBox "Saved to " & f, , "XL n CAD"
End Sub
How to run the macro
- AutoCAD 2010 and later need the free VBA Enabler (VBA module) from Autodesk for your version. AutoCAD LT doesn’t support VBA.
- Save the drawing first: the file is written to the drawing’s folder.
- Type
VBAIDE(or press Alt + F11), choose Insert → Module, and paste the code. - Close the editor, type
VBARUN(or Alt + F8), pick the macro and click Run. - 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 |
|---|---|---|
| Vertex count divided by 2 | Wrong count: each 3D vertex has three values | Divided by 3 |
| Label said LW Polyline | Wrong object name in the output | Removed |
| Curly quotes “ ” | The code won’t run | Straight quotes |
| Selecting another object | Crashed with Type mismatch | Checks the type first |
Things to know
- The length is the true 3D length along the slope, not the plan length.
- For the plan (2D) length, flatten a copy or calculate it in Excel from the X and Y columns.
- For normal 2D polylines, use the 2D polyline macro.