首页 > 解决方案 > 使用 VBA Loop 绘制 AutoCAD 多段线

问题描述

我正在尝试从 Excel 表的数据中绘制一条折线,我已经手动实现了它,但我想知道是否有一个带有循环的过程,可以让我在拥有更多数据的情况下更有效率。

Option Explicit

Sub polyline()

Dim vertexlist(0 To 8) As Double
Dim poli As Object

vertexlist(0) = Range("B11")
vertexlist(1) = Range("C11")
vertexlist(2) = Range("D11")

vertexlist(3) = Range("B12")
vertexlist(4) = Range("C12")
vertexlist(5) = Range("D12")

vertexlist(6) = Range("B13")
vertexlist(7) = Range("C13")
vertexlist(8) = Range("D13")

Set poli = AutoCAD.Application.ActiveDocument.ModelSpace.AddPolyline(vertexlist)

poli.Closed = True

End Sub

我将非常感谢您的帮助。问候

Excel文件

标签: excelvbaautocad

解决方案


请尝试下一个改编的代码。未经测试,我没有安装 AutoCad,但这应该是要遵循的逻辑:

Sub polyline()
  Dim sh As Worksheet, vertexlist() As Double, firstRow As Long, lastRow As Long, poli As Object, i As Long, k As Long

 Set sh = ActiveSheet
 lastRow = sh.Range("B" & sh.rows.count).End(xlUp).row
 firstRow = 11
 ReDim vertexlist((lastRow - firstRow + 1) * 3 - 1) '  -1 because the array is zero based
 For i = firstRow To lastRow
     vertexlist(k) = Range("B" & i).Value: k = k + 1
     vertexlist(k) = Range("C" & i).Value: k = k + 1
     vertexlist(k) = Range("D" & i).Value: k = k + 1
 Next i

 Set poli = AutoCAD.Application.ActiveDocument.ModelSpace.AddPolyline(vertexlist)
 poli.closed = True
End Sub

推荐阅读