Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: VB6 - Use a variable within a variable's name  (Read 11587 times)

0 Members and 1 Guest are viewing this topic.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
VB6 - Use a variable within a variable's name
« on: August 20, 2010, 07:28:06 PM »
Is it possible to use a variable's value to influence a new variable's name? In batch, one could do this:
Code: [Select]
set variable=1
set newvar%variable%=hello world <--- I need this line in VB6
echo %newvar1%
But I'm having a little trouble trying to pull this off in VB. It would save quite a bit of code if this was possible.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #1 on: August 20, 2010, 07:41:52 PM »
Is it possible to use a variable's value to influence a new variable's name? In batch, one could do this:
Code: [Select]
set variable=1
set newvar%variable%=hello world <--- I need this line in VB6
echo %newvar1%
But I'm having a little trouble trying to pull this off in VB. It would save quite a bit of code if this was possible.

What are you trying to do? By which I mean, what are you doing that this would save time with?
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #2 on: August 20, 2010, 07:59:29 PM »
I'm making a program (just for the *censored* of it) which pretty much monitors a workplace (hypothetically speaking), in which the user (the manager) sets up how many workers there are, who they are, how much they work, etc. All the controls which display information and the timers are in control arrays (with an array value for each worker). Problem is, I have to repeat the same code over and over with different variables, the only change being a sequential number at the end of the variable name.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #3 on: August 20, 2010, 08:00:35 PM »
Problem is, I have to repeat the same code over and over with different variables, the only change being a sequential number at the end of the variable name.


Use Arrays or collections instead.
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #4 on: August 20, 2010, 08:03:01 PM »
#1 Arrays can be used with variables?
#2 Collections?
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #5 on: August 20, 2010, 08:38:10 PM »
#1 Arrays can be used with variables?

Of course they can. Control arrays are a deviant structure that simulates a normal array very badly. You could create User Defined type to store employee data, and then have an array of those types:
Code: [Select]
Option Explicit
Public Type EmployeeData
    FirstName As String
    LastName As String
    HoursWorked As Long
   

End Type
Private Employees() As EmployeeData
Private EmployeeCount As Long
Private CurrentEmployee as Long



CurrentEmployee indicates the current index into the array.

Wether you have "Next" or "Previous" buttons to move through the data or wether you use a list or some other control to switch between them, the first thing you need is special handling in your various editing controls (in this case, three- first name, last name, and hours worked) that either change the "current" employeedata or break out if EmployeeCount is 0.

Adding a new Employee:

Code: [Select]
Private Sub CmdAdd_Click()

EmployeeCount=EmployeeCount+1
Redim Preserve Employees(1 to EmployeeCount)
CurrentEmployee=EmployeeCount
RefreshView()


End Sub

This adds a new item, and then refreshes the controls displaying state. It calls the following routine to do that:

Code: [Select]
Private Sub RefreshView()
If CurrentEmployee=0 then Exit Sub
txtFirstName.Text = Employees(CurrentEmployee).FirstName
txtLastName.Text = Employees(CurrentEmployee).LastName
txtHoursWorked.Text = Employees(CurrentEmployee).HoursWorked
if(currentemployee) = Ubound(Employees) then cmdNext.Enabled=False Else cmdNext.Enabled=True
if(currentemployee) = Lbound(Employees) then cmdPrev.Enabled=False Else cmdPrev.Enabled=True
End Sub


To move between the various employees, you merely change the "CurrentEmployee" variable and refresh the view again:

Code: [Select]
private sub CmdNext_Click()
    CurrentEmployee=CurrentEmployee+1
    RefreshView()
End Sub
Private Sub CmdPrev_Click()
    CurrentEmployee=CurrentEmployee-1
    RefreshView()
End Sub


And so on.

The various text boxes in question  (txtFirstName,txtLastName, txtHoursWorked) can be used to update the "current" employee.

You can either take advantage of the Change event, or use a "Save" button, or save in the cmdNext and cmdPrev routines:

Code: [Select]
Private Sub SaveEmployee()
With Employees(CurrentEmployee)
    .FirstName=txtFirstName.Text
    .LastName = txtLastName.Text
    .HoursWorked = Val(txtHoursWorked.Text)
End With
End Sub

Then, wherever you need to "save" the current value (either a Specified Save button, in the next or previous buttons, etc) you simply call "SaveEmployee".

Removing an Employee is a tad more tricky. We need to Remove an element, and this is done by moving all the higher elements down one index. You can do this manually:

Code: [Select]
Private Sub RemoveEmployee(RemoveIndex as Long)
Dim I as Long
For I = RemoveIndex to Ubound(Employees)-1
    Employees(RemoveIndex) = Employees(RemoveIndex+1)
Next
EmployeeCount=EmployeeCount-1
Redim Preserve Employees(EmployeeCount)




Quote
#2 Collections?


The other option is, instead of using a User Defined Type, you could define an "Employee" Class Module and keep a collection of them. Slightly more "involved" in a few ways, but a lot more flexible as well.
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #6 on: August 20, 2010, 09:03:50 PM »
Wow...I guess that explains why it took so long for a reply, lol  :D

I'm not quite sure how to implement this into my program, as all the information is being displayed at once, in multiple controls.

I basically decided to follow through with just copying and pasting the code over and over, it wasn't so hard, only 5 changes per paste.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #7 on: August 20, 2010, 09:10:22 PM »
I'm not quite sure how to implement this into my program, as all the information is being displayed at once, in multiple controls.

Personally, I would start over, and redesign it from scratch. From the sounds of things it doesn't sound too complicated, you've just overcomplicated it with multiple unnecessary control arrays.
I was trying to dereference Null Pointers before it was cool.

Salmon Trout

  • Guest
Re: VB6 - Use a variable within a variable's name
« Reply #8 on: August 21, 2010, 08:34:08 AM »
This question, "how do I make variable1, variable2 ... variableN?", is the classic indicator that the person needs to find out about arrays. You often see it the other way around as "how do I implement arrays in batch?"


ghostdog74



    Specialist

    Thanked: 27
    Re: VB6 - Use a variable within a variable's name
    « Reply #9 on: August 21, 2010, 10:24:01 AM »
    @helpmeh, what you basically want is arrays. But i think vb6 ( its been a long time) doesn't have arrays that can use strings as the index for the arrays (called dictionaries or hashes). Later implementation of vb may make use of the dictionary object (or collections), like those in vbscript.

    BC_Programmer


      Mastermind
    • Typing is no substitute for thinking.
    • Thanked: 1140
      • Yes
      • Yes
      • BC-Programming.com
    • Certifications: List
    • Computer: Specs
    • Experience: Beginner
    • OS: Windows 11
    Re: VB6 - Use a variable within a variable's name
    « Reply #10 on: August 21, 2010, 11:14:21 AM »
    @helpmeh, what you basically want is arrays. But i think vb6 ( its been a long time) doesn't have arrays that can use strings as the index for the arrays (called dictionaries or hashes). Later implementation of vb may make use of the dictionary object (or collections), like those in vbscript.

    VB can either use the built in Collection object:

    Code: [Select]
    Private Sub Test_Collection()
    Dim Col as Collection
    Set Col = new Collection
    Col.Add "Dog","Woof"
    Col.Add "Cat","Meow"
    Col.Add "Cow","Moo"
    Msgbox Col.Item("Dog") 'Shows "Woof"
    Msgbox Col!Dog 'Also shows "Woof" (! is a freaky weird Collection operator)


    End Sub

    The collection object is rather tricky to use in many situations, since you cannot map the value back into the key (since you no longer have access to any of the keys).

    Of course you can always reference the Scripting Runtime, where you can find the very same dictionary object that is exposed by the script host. You don't even need to reference them, actually, if you use late binding:

    Code: [Select]
    Public Sub testdictionary()
    Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")
    dict.Add "Dog", "Woof"
    dict.Add "Cat", "Meow"
    dict.Add "Cow", "Moo"

    MsgBox dict.Item("Dog")
    MsgBox dict!Dog




    End Sub

    Of course this looks exactly the same as the collection example, but the dictionary has as you know a number of other useful properties/methods, including being able to retrieve the item keys. It has the slight disadvantage in that you cannot use a numeric index as you can for a collection.

    With VB.NET there are a number of choices. you could simply create a List<T> of the specified type T (String, int, whatever) or you could create a sort of dictionary by creating a List<KeyValuePair<String,Object>>, then you can use Linq to acquire values from it:

    Code: [Select]
    //assume _list is of type List<KeyValuePair<String,Object>>, skey is the key for the item we want.
    queryget = from var x in _list where x.Key.Equals(skey,StringComparison.OrdinalIgnoreCase) select x;
    foreach(var loopval in queryget)
    {
    //loopval is a KeyValuePair<String,Object> whose Key field matches skey.


    }

    And, if you were REALLY crazy, you could use an actual dictionary (but real men just fake it with Lists of KeyValuePairs):


    Code: [Select]
      public static void testdictionary()
            {

                Dictionary<String, String> dicty = new Dictionary<string, string>();


                dicty.Add("Dog", "Woof");
                dicty.Add("Cat", "Meow");
                dicty.Add("Cow", "Moo");

                Debug.Print(dicty["Dog"]);
                foreach (var q in (from x in dicty where x.Key.StartsWith("C", StringComparison.OrdinalIgnoreCase) select x).ToArray())
                {
                    Debug.Print(q.Key + "=" + q.Value);
                }


            }
    which gives us the following in the debug window:

    Woof
    Cat=Meow
    Cow=Moo


    All of this can be done in VB.NET (using the  various classes in System.Collections.Generic) but I'm not sure of the syntax.

     (Dim Variable as List(Of KeyValuePair(Of String,String)) or something like that.
    I was trying to dereference Null Pointers before it was cool.

    ghostdog74



      Specialist

      Thanked: 27
      Re: VB6 - Use a variable within a variable's name
      « Reply #11 on: August 21, 2010, 02:01:40 PM »
      when i look at how its implemented in VB, i can't help but wonder why its not as simple and straightforward to use as in Perl/Python.

      Salmon Trout

      • Guest
      Re: VB6 - Use a variable within a variable's name
      « Reply #12 on: August 21, 2010, 02:06:51 PM »
      Why oh why can't Visual Basic be more like Python? Or Perl? Or APL?



      Fleexy



        Intermediate

      • OW NEXT TIME I SHOULD TURN IT OFF BEFORE SERVICING
      • Thanked: 2
        • Yes
        • Yes
      • Experience: Experienced
      • OS: Windows XP
      Re: VB6 - Use a variable within a variable's name
      « Reply #13 on: August 21, 2010, 03:13:09 PM »
      Why can't Perl and Python be like VB? ;)
      I love .NET!

      ghostdog74



        Specialist

        Thanked: 27
        Re: VB6 - Use a variable within a variable's name
        « Reply #14 on: August 21, 2010, 04:07:31 PM »
        Why can't Perl and Python be like VB? ;)
        You want Perl/Python to be like VB ? in what sense? And have you used Python/Perl before?