2

To switch between single and double precision in C we use something like:

#ifdef USE_DOUBLE
typedef double data_t;
#else
typedef float data_t;
#endif

Is there an easy way to perform the same thing so that I can easily switch between the two in VBA?

0

2 Answers 2

1

In VBS, user defined types are abstracted as Classes. For e.g.

Public Const PRECISION = 1

Class data_t
    Private dValue

    Private Sub Class_Initialize
        dValue = 0
    End Sub

    Public Property Get Value 'inside out
        Value = dValue
    End Property

    Public Property Let Value(val) 'outside in
        If PRECISION = 1 Then
            dValue = CSng(val)
        Else
            dValue = CDbl(val)
        End If
    End Property    
End Class

Set obj = New data_t
obj.Value = 0.00000011920928955078125
Msgbox obj.Value

If PRECISION = 1, the output would be 1.192093E-07

Else the output would be 1.19209289550781E-07

You can easily modify the above code in VBA by adding a class module.

2
  • This is a nice solution but is it efficient performance-wise?
    – z̫͋
    Apr 1, 2014 at 14:48
  • Its as efficient (or inefficient) as creating/using any object. Apr 1, 2014 at 15:53
0

This works nearly the same in VBA:

#Const USE_DOUBLE = False

#If USE_DOUBLE Then
    Public data As Integer
#Else
    Public data As Double
#End If

The # stands for conditional compilation.

2
  • It's not exactly the same, using this code I would have to put this condition on every variable, whereas in C I put the condition once on the type declaration and declare the variables as type "data"
    – z̫͋
    Apr 1, 2014 at 11:37
  • Oh, yeah I misunderstood your code. But still, this is the only way that works in VBA... Apr 1, 2014 at 11:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.