VBA:有关自定义类型和函数的更多问题

时间:2016-09-15 07:58:37

标签: vba user-defined-types

我试图将数组变量(自定义类型)传递给函数时遇到困难。使用D1调用该函数会出现错误,请问我在这里遇到什么问题?

我已经尝试声明D1()等似乎不正确但无论如何都无法正常工作。

Public Type CusType
    One_ As Integer
    Two_ As Single
    Thr_ As Single
    Fou_ As Single
End Type

Public Sub Test1()
    Dim D1 As CusType
    Dim D2 As CusType
    Dim D3 As CusType
    Dim Marker As Integer

    Marker = 1

    With D1
        .One_ = 11
        .Two_ = 12
        .Thr_ = 13
        .Fou_ = 14
    End With

    With D2
        .One_ = 21
        .Two_ = 22
        .Thr_ = 23
        .Fou_ = 24
    End With

    With D3
        .One_ = 31
        .Two_ = 32
        .Thr_ = 33
        .Fou_ = 34
    End With

    Dim TestResult As CusType
    TestResult = Test(Marker, **D1, D2, D3**)

    Debug.Print TestResult.One_ & ","; TestResult.Two_ & ","; TestResult.Thr_ & ","; TestResult.Fou_
End Sub

Public Function Test(R, A, B, C) As CusType
    Dim First, Second, Third, Fourth As Single

    If R = 0 Then
        Test = A
    ElseIf R = 1 Then
        Test = B
    Else
        Test = C
    End If
End Function

1 个答案:

答案 0 :(得分:2)

错误消息清楚地告诉您:

  

只有在公共对象模块中定义的用户定义类型才能被强制转换为变体或从变体强制传递或传递给后期绑定函数

(在问题中包含确切的错误消息会很有帮助。)

您没有为Test声明参数和返回类型,因此您的结构将被强制转换为Variant

声明类型:

Public Function Test(ByVal R As Long, A As CusType, B As CusType, C As CusType) As CusType