I'm trying to update Textbox values using an assigned array. It seems I'm able to update "Item" Itself but not the object? Anyone have some pointers on how to approach this better?
This is what I have so far. I'm not sure how to set objects properly to an array either.
Dim spcList(1 To 3) As Integer
Dim item As Variant
spcList(1) = Me.txt1.Value
spcList(2) = Me.txt2.Value
spcList(3) = Me.txt3.Value
' Spacing Error Handling
For Each item In spcList:
item = 0.875
Debug.Print item
Next
CodePudding user response:
My VBA is rusty, but I believe for this purpose things work pretty much the same as in VB.Net, with which I'm a little more current. That disclaimer out of the way, let's continue.
If you want to replace the value in the array, as the code in the question is attempting to do, whether an integer or something more complex like a reference, you must use a traditional For
loop:
Dim i As Integer
For i = 1 To 3
spcList(i) = 0.875
Next
This is because the loop variable in a For Each
statement gets a copy of the value from the collection. So for an integer, like here, the original code would only assign over the copy held in the variable.
To expand on what's happening and hopefully deepen your understanding of the language, let's also look how the original code would treat a reference type. In this case the loop variable still gets a copy, but not of the entire object: only the reference. This works because the copy still refers to the same object in memory.
Therefore, assigning a new object reference to the loop variable would have the same result as with the simpler Integer type, and the object reference in the array would not change, because we only replaced the copy. However, if you were to call a method on the loop variable, or assign to a property of the object, those things would work more as you expect, because (again) the copied reference in the loop variable still refers to the same object in memory and so you are acting on that object's state.