How to address a variable

User avatar
ErikJan
BronzeLounger
Posts: 1255
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

How to address a variable

Post by ErikJan »

I have a variable defined like this:

Type MyVar
V1 as Integer
V2 as String
V3 as ..
...
Vx as ...
End Type

I want to call a subroutine with the name of the sub variables and get the value back...

So this call: MySub("V7"), should return the value in MyVar.V7

Is this possible? I Suspect I need some 'indirect' approach...

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: How to address a variable

Post by HansV »

MyVar is a type, not a variable. So MyVar.V7 doesn't have a value.
If you have a variable W of type MyVar, W.V7 has a value.
But as far as I know, you can't refer to members of W indirectly.
Perhaps an array would be more suitable for your purpose.
Best wishes,
Hans

User avatar
ErikJan
BronzeLounger
Posts: 1255
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

Re: How to address a variable

Post by ErikJan »

Yes, sorry, that's how I do it. Pity it can't be done... now I have to be 'creative' somehow (of use an array, but that would require complete code rewrite..)

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: How to address a variable

Post by HansV »

You could use a Select Case, but that seems rather cumbersome to me:

Code: Select all

Function GetVal(MemberName As String) As Integer
    Select Case MemberName
        Case "V1"
            GetVal = W.V1
        Case "V2"
            GetVal = W.V2
        Case "V3"
            GetVal = W.V3
        ' etc etc
    End Select
End Sub
An array is *much* simpler. Or perhaps a collection or dictionary object? You can refer to a member of a collection/dictionary through its key (a string).
Best wishes,
Hans

User avatar
rory
5StarLounger
Posts: 817
Joined: 24 Jan 2010, 15:56

Re: How to address a variable

Post by rory »

Or use a class instead of a type, then use Callbyname
Regards,
Rory

User avatar
Jan Karel Pieterse
Microsoft MVP
Posts: 656
Joined: 24 Jan 2010, 17:51
Status: Microsoft MVP
Location: Weert, The Netherlands

Re: How to address a variable

Post by Jan Karel Pieterse »

I was about to try callbyname. Doesn't it work for a variable?
Regards,

Jan Karel Pieterse
Excel MVP jkp-ads.com

User avatar
rory
5StarLounger
Posts: 817
Joined: 24 Jan 2010, 15:56

Re: How to address a variable

Post by rory »

The first argument has to be an object unfortunately.
Regards,
Rory

User avatar
Jan Karel Pieterse
Microsoft MVP
Posts: 656
Joined: 24 Jan 2010, 17:51
Status: Microsoft MVP
Location: Weert, The Netherlands

Re: How to address a variable

Post by Jan Karel Pieterse »

Makes sense.
Regards,

Jan Karel Pieterse
Excel MVP jkp-ads.com