0

I am trying to calculate something in Excel VBA using a class definion. The main goal is to calculate in an class within the sub Calc1 a simple ratio. When executing the module I receive the following error:

function or variable expected

in the line of the module

MsgBox myCalc1.Calc1

The code is below

Class is defined as the following:

' These are properties
Public dat_date1 As Date
Public dat_date2 As Date
Public str_Option As String
Dim ratio As Double
Dim nominator As Double
Dim denominator As Double

' These are methods
Sub Calc1()
    ' Code for day count conventions
    If str_Option= "o1" Then
        nominator = (dat_date2-dat_date1)
        denominator = 2
    ElseIf str_Option = "o2" Then
        nominator = (dat_date2-dat_date1)
        denominator = 3
    Else
        MsgBox "No function defined"
    End If

    ratio = nominator / denominator
End Sub

My module is defined as the following:

Sub ModuleCalc()

    Dim myCalc1 As clsCalc

    Set myCalc1 = New clsCalc
    With myCalc1 
        .dat_date1 = "01/02/2015"
        .dat_date2 = "28/02/2015"
        .str_Option= "o1"
    End With

    MsgBox myCalc1.Calc1
End Sub
11
  • Unless you specifically need a string an enum is a better choice for o1 Commented Jun 13, 2017 at 12:55
  • @AlexK., thanks for the quick reply. was a typo but still get the same error message Commented Jun 13, 2017 at 12:56
  • Function Calc1() - not Sub Calc1() Commented Jun 13, 2017 at 12:57
  • @braX Doesn't matter - it doesn't return anything anyway. Commented Jun 13, 2017 at 12:58
  • 1
    Calc1 returns nothing to the MsgBox call is not valid. Commented Jun 13, 2017 at 13:05

1 Answer 1

2

Your actual error is because Calc1 isn't a function, so it doesn't return a value and therefore you can't pass it as an argument to a message box object.

I suspect your function should look like this:

Function Calc1() As Double
    ' Code for day count conventions
    If str_Option= "o1" Then
        nominator = (dat_date2-dat_date1)
        denominator = 2
    ElseIf str_Option = "o2" Then
        nominator = (dat_date2-dat_date1)
        denominator = 3
    Else
        MsgBox "No function defined"
    End If

    Calc1 = CDbl(nominator / denominator)
End Sub

Now you can use it to pass the value back to a message box.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. It works. Missed it using a function instead of Sub :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.