Search code examples
vbaexcelexcel-2013

How to turn a range value to a double (VBA)


So I want to make a function that takes a value in a cell to make some calculations, but whenever I try to get the value from the cell rather than hard-code it I get a #VALUE! error whenever the function is run. Whereas this did not happen when the value is hard-coded.

I believe that this is because the Range.Value returns a Variant, but I don't know how to turn the data to a double so that the function works right.

Function IfMissionarySupplies(Missionary_Type As String) As Double
Wb = ThisWorkbook 'Wb is a global variable.
Dim Elder_Supplies, Sister_Supplies As Double
Elder_Supplies = Workbooks(Wb).Worksheets("Control Variables").Range("C11").Value
Sister_Supplies = Workbooks(Wb).Worksheets("Control Variables").Range("C14").Value
If Missionary_Type = "Sisters" Then
    IfMissionarySupplies = Sister_Supplies
    Exit Function
ElseIf Missionary_Type = "Elders" Then
    IfMissionarySupplies = Elder_Supplies
End If 
End Function

I've searched over and over in the internet, but to no avail. I am also new to VBA so I might be overlooking something obvious to more experienced VBA developers.

Thanks!


Solution

  • I put the following in a standard module:

    Function IfMissionarySupplies(Missionary_Type As String) As Double
        Wb = ThisWorkbook.Name 'Wb is a global variable.
        Dim Elder_Supplies, Sister_Supplies As Double
    
        Elder_Supplies = Workbooks(Wb).Worksheets("Control Variables").Range("C11").Value
        Sister_Supplies = Workbooks(Wb).Worksheets("Control Variables").Range("C14").Value
    
        If Missionary_Type = "Sisters" Then
            IfMissionarySupplies = Sister_Supplies
            Exit Function
        ElseIf Missionary_Type = "Elders" Then
            IfMissionarySupplies = Elder_Supplies
        End If
    End Function
    

    and setup the worksheet as follows:

    enter image description here

    So the above version of your UDF does appear to work!