简体   繁体   中英

VBA how to output class module (object) from function to excel worksheet, and using that output as input for another function?

Suppose I have 2 class modules named 'myFruits':

Public nApples As Integer
Public nOranges As Integer

and 'fruitPrice':

Public Apple As Double
Public Orange As Double

I want to write 3 functions/modules 'showFruits', 'showPrice' and 'getValue' which I can call in excel worksheet, with inputs and outputs below, and able to display/print in the excel sheet in this manner: https://imgur.com/a/fGNoHCz

The first two functions' outputs (class objects) will be inputs for the third function, 'getValue', which returns the value of number of fruits * fruit price.

I'm familiar with Python but new to VBA, and I'm having trouble finding resources that do exactly this. Any help is appreciated!

This is my attempt so far:

1.

Function showFruits(nApples As Integer, nOranges As Integer) As myFruits

    Set showFruits = New myFruits

    showFruits.nApples = nApples
    showFruits.nOranges = nOranges

    'How to print above variables in excel?
    'How to use the output object of this function as input for another function in excel?

End Function
Function showPrice(pApple As Double, pOrange As Double) As fruitPrice

    Set showPrice = New fruitPrice

    showPrice.Apple = pApples
    showPrice.Orange = pOranges

    'How to print above variables in excel?
    'How to use the output object of this function as input for another function in excel?

End Function
Function getValue(showFruits As myFruit, showPrice As fruitPrice)

    'How to pass the output objects as input to this function in excel?

    Dim total As Double
    total = showFruits.nApples * showPrice.Apple + showFruits.nOranges * showPrice.Orange
    getValue = total

End Function

A lot going on here, but I'm not sure I understand why you're using a Class Module at all.

For the function piece, check out documentation on Creating custom functions in Excel . I've always called these User Defined Functions , so you might find some luck searching for that as well.

Something like this to get started:

Function showFruits(nApples) As String

'How to print above variables in excel?
'Simply assign a value/output/something to your function

showFruits = "Apples: " & nApples

End Function

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