+ Reply to Thread
Results 1 to 4 of 4

Can I build variable names in a VBA loop?

  1. #1
    Valued Forum Contributor
    Join Date
    06-19-2010
    Location
    Holywell, N Wales, UK
    MS-Off Ver
    Excel 2013
    Posts
    470

    Can I build variable names in a VBA loop?

    ]Hi Everyone
    Another sort of INDIRECT() query please.

    I want to build variable names dynamically within a loop and then use them as variables.
    For example VarName1, VarName2,VarName3 etc.

    I have seen suggestions that I could use arrays such as VarName(1), VarName(2) etc.

    The twist in the tail is that I also want to dynamically build the array variable names and then use them - so to access element 1 of the different arrays:
    VarName1(1), VarName2(1), VarName3(1).

    How can a string be evaluated as a variable and can this be done in VBA please?

    Any code examples gratefully received.

    as ever TIA

    barry
    Last edited by barryleajo; 09-20-2010 at 12:27 PM.

  2. #2
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2010
    Posts
    40,678

    Re: Can I build variable names in a VBA loop?

    You could add variables to a collection or dictionary. If a collection, you would reference the variable by index, if a dictionary, by key.

    See the VB Language Reference for both objects. The latter requires a reference to Microsoft Scripting Runtime for early binding.

    All that said, in most cases I can imagine, there is a better, simpler way.
    Entia non sunt multiplicanda sine necessitate

  3. #3
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,435

    Re: Can I build variable names in a VBA loop?

    Use a 2 dimensional array.

    VarName(1,1), VarName(2,1), VarName(3,1)
    Cheers
    Andy
    www.andypope.info

  4. #4
    Valued Forum Contributor
    Join Date
    06-19-2010
    Location
    Holywell, N Wales, UK
    MS-Off Ver
    Excel 2013
    Posts
    470

    Re: Can I build variable names in a VBA loop?

    Thanks Guys
    These couple of nudges in a couple of directions will definitely get me going again.
    This just seems to be a relatively 'obvious' thing to want to do but doesn't (to me) appear to be implemented that straightforwardly in VBA (or maybe it's me that isn't is straightforward!)

    With appreciation for your help and experience again.
    I have marked as solved and will tip your scales
    barry

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1