简体   繁体   中英

VBA - user defined type not defined

All my searches for this error did not help. This should be simple... My trivial module [named FTA] contains this code:

Public Type AddMult
    Added As Double
    Multiplied As Double
End Type

Function test(A As Double, B As Double) As AddMult
    test.Added = A + B
    test.Multiplied = A * B
End Function

The module compiles cleanly. Then, trying to set a worksheet cell value to one of the type members returned by the function, I use the syntax below.

=test.added(1,2)

It results in "User-defined type not defined" popup error and the cell displays #NAME?. How do I get it do display the correct value 3? As you can imagine this is not about trivial math, instead it is about ability to invoke a function that returns a Type, and then use one member of that Type in the worksheet. My Excel is part of Office Professional Plus 2010.

You could create two functions that are usable as UDFs, and then have each of those functions invoke your existing one, eg:

Public Type AddMult
    Added As Double
    Multiplied As Double
End Type

Function test(A As Double, B As Double) As AddMult
    test.Added = A + B
    test.Multiplied = A * B
End Function

Function test_added(A As Double, B As Double) As Double
    test_added = test(A, B).Added
End Function

Function test_multiplied(A As Double, B As Double) As Double
    test_multiplied = test(A, B).Multiplied
End Function

You can then use =test_added(1,2) in an Excel cell.

This is in addition to YowE3K, although their example is really the best option. This uses an optional Boolean to see which value from AddMult to return

Public Type AddMult
    Added As Double
    Multiplied As Double
End Type

Function test(A As Double, B As Double, Optional returnMulti As Boolean = False) As Double
Dim am As AddMult
    am.Added = A + B
    am.Multiplied = A * B
    If returnMulti = True Then
        test = am.Multiplied
    Else
        test = am.Added
    End If
End Function

I had this issue, and found making sure to define the types at the start of the module, before the subs solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM