使用数组函数时为什么会出现错误

时间:2020-03-19 19:19:13

标签: arrays vba autocad

我测试了此Autocad VBA例程。有效。没问题。

Sub Add_Line_1()
    Dim n1(2) As Double, n2(2) As Double
    Dim r As AcadLine
    n1(0) = 100
    n1(1) = 150

    n2(0) = 220
    n2(1) = 230
    Set r = ThisDrawing.ModelSpace.AddLine(n1, n2)
End Sub

但是。我想使用Array函数。没用发生错误。

运行时错误5:无效的过程调用或参数

Sub Add_Line_2()
    Dim n1 As Variant, n2 As Variant
    Dim r As AcadLine
    n1 = Array(100#, 150#)
    n2 = Array(220#, 230#)

    ' ERROR LINE.
    Set r = ThisDrawing.ModelSpace.AddLine(n1, n2)
End Sub

如何在此代码中使用Array函数?

编辑: 我尝试了此代码,但再次出错

编译错误。无法分配给数组

Sub Add_Line_3()
    Dim n1(2) As Double, n2(2) As Double
    Dim r As AcadLine
    n1 = Array(100#, 150#, 0#) 'ERROR LINE
    n2 = Array(220#, 230#, 0#)

    Set r = ThisDrawing.ModelSpace.AddLine(n1, n2)
End Sub

1 个答案:

答案 0 :(得分:1)

如果只是为了简化代码,则可以使用辅助函数。

假设我们正在谈论2D / 3D空间中的一个点,我们可以定义:

Function Point(x As Double, y As Double, Optional z As Double = 0) As Double()
    ReDim temp(2) As Double
    temp(0) = x
    temp(1) = y
    temp(2) = z
    Point = temp
End Function

并使用

ThisDrawing.ModelSpace.AddLine(Point(100, 150), Point(220, 230))