Stepping up an array in a loop vb - arrays

This code simply completes a shift of characters for every negative variable in the loop. It then displays this text for every loop completed. (The name variable is actually a parameter for one of the subroutines, so does need to remain being called 'variable')
Counter = 0
dim counterarray(24)
For variable = -1 to -25
completeshift()
displaytext()
counter = counter + 1
next
So in this code, i would like to know how to step up each variable in the array every time the loop is complete. Basically i need the first
loop displaytext() to go into counterarray(0), the second to go into counterarray(1) etc until all of them have been completed.

Not entirely sure what your question is, but if you want that loop to work you need to add step - 1
For variable = -1 to -25 step -1
completeshift()
displaytext()
counter = counter + 1
next

You are not using variable for anything so you may as well write,
Dim counterarray(24)
For i = 0 to 24
completeshift()
counterarray(i) = displaytext()
Next
probably too elaborate but ...
Dim count = 25
Dim counterArray(count - 1) As String
Enumerable.Range(0, count).Zip(Enumerable.Range(-count, count).Reverse(),
Function(counter, variable) counterArray(counter) = DisplayText())

Related

Are my arrays incompatible?

I am trying to loop through an array that contains split strings, done via this line:
repHolder() = Split(rep, ",")
That's all fine and good, however, when I try to loop through this repHolder() array via a for loop, I am met each time with a subscript out of range error.
This makes no sense to me. When I step through the array it fails on the first element every time; this line:
If repHolder(j) = counter Then
I tried setting j to 0 and 1, both of which failed on the first sequence of the loop. This suggests to me because the array doesn't have a defined size; that I cannot loop through it this way, but that still makes little sense to me as it is still filled with elements.
Here is the entire code block of what I am trying to do:
Dim repHolder() As String
Dim strHolder() As String
Dim counter As Variant
Dim j As Integer
For Each rep In repNames()
repHolder() = Split(rep, ",")
Next rep
For Each rangeCell In repComboRange
k = 1
Do
If rangeCell.Value = repCombos(k) Then 'At this point, if rangecell = repcombos(k)
Range(rangeCell, rangeCell.End(xlToRight)).Copy
strHolder() = Split(rangeCell.Value, "/")
For Each counter In strHolder()
Stop
For j = 1 To 17
If repHolder(j) = counter Then
You are looping through repNames() and setting this new array via split (over and over again for each repName element...)
For Each rep In repNames()
repHolder() = Split(rep, ",")
Next rep
Every iteration of this loop resets repHolder() to a split of the rep element dropping whatever values were just set in that array in the previous iteration. So once it's done only the last element of RepNames() has been split into the repHolder() array.
For instance, if RepNames() looks like:
Element 0: "james,linda,mahesh,bob"
Element 1: "rajesh,sam,barb,carrie"
Element 2: ""
Then after all this iterating your repHolder array is going to be empty because there is nothing in the final element.
Stick a breakpoint (F9) on you For Each rangeCell In repComboRange line and look at your Locals pane in VBE. Check out the values that are stored in your repHolder() array at that point in time. I suspect there will be nothing in there.
The other oddball here is that you are looping 1 through 17. repHolder() will be a 0-based array so that should be 0 through 16. But... even that is nonsense since this really only makes sense as a For Each loop (or to use the uBound(repHolder) to determine how many times to loop:
For Each counter In strHolder()
Stop
For each repHolderElem in repHolder
If repHolderElem = counter Then
....
Next repHolderElem

Exiting Nested For loop VBA and re-looping

I'm trying to work with a nested For loop. I essentially have 2 arrays and I want to use the 1st variable in array1 with the 1st variable in array2 to do some operation, and so on until the array is exhausted. Unfortunately, the Exit For, doesn't exit for the For levels. So I've tried to use a goTo command, however then I get an error of "This array is fixed or temporarily locked" clearly because I'm trying to re-access the array. I'm stuck how to get around this in VBA. Below is my code where at MsgBox some operation (that will need the pairs (dAFL,AFL),(dSF,SF), etc) will take place:
For Each vN In Array(dAFLcell, dSFcell, dSOcell, dFIGcell, dIBAcell, dIBXcell)
a = 0
For Each vN2 In Array(AFLcell, SFcell, SOcell, FIGcell, IBAcell, IBXcell)
If i = a Then
MsgBox a
GoTo end_of_for
End If
a = a + 1
Next vN2
end_of_for:
i = i + 1
Next vN
You could use a boolean flag - I don't know that it's the accepted method, but I use it from time to time.
Dim skipBool as Boolean = False
For Each vN In Array(dAFLcell, dSFcell, dSOcell, dFIGcell, dIBAcell, dIBXcell)
a = 0 'I think you want this out here, otherwise a will always equal 0
For Each vN2 In Array(AFLcell, SFcell, SOcell, FIGcell, IBAcell, IBXcell)
If Not skipBool Then 'run this stuff only if we don't want to skip it (duh!)
If i = a Then
MsgBox a
skipBool = True 'set skipBool to be True (we want to skip it!)
End If
a = a + 1
End If
Next vN2
i = i + 1
skipBool = False 'reset skipBool for the next go around
Next vN
I'm sure this code can be optimized a bit further (and to be honest, I haven't tested it), but it looks like this is what you're going for.
To be honest, the only problem might be that a = 0 was inside the second for loop, and that's why you weren't getting the results you expected. It's been a while since I've used VBA (I've only been using VB.NET), so I don't remember the exact syntax there. I'd try fixing that, and going back to the exit for method. If it still doesn't work, my code should.
Here's another possible approach:
Dim vn, Vn2 As Variant
Dim i, min As Integer
vn = Array(dAFLcell, dSFcell, dSOcell, dFIGcell, dIBAcell, dIBXcell)
Vn2 = Array(AFLcell, SFcell, SOcell, FIGcell, IBAcell, IBXcell)
If UBound(vn) <= UBound(Vn2) Then
min = UBound(vn)
Else
min = UBound(Vn2)
End If
For i = LBound(vn) To min
If vn(i) = Vn2(i) Then
MsgBox vn(i)
Exit For
End If
Next i

Loop variable ends with a value one above expected

In VBA, running in Excel, I am running a basic loop that fills an array with values. The code is as below.
What I find curious, is the value of Counter starts at 0, yet ends at 7, rather than 6. I can note this when I'm looking in the Locals window and running the code step-by-step. It seems the value becomes 7 on its last instance of running 'Next'
Is this normal, or is there something I'm doing wrong?
It doesn't seem to change the outcome here, but if I'm using more complicated code, I want to be sure this is what I should be expecting.
Sub ArrayLoop()
Dim myArray(6) As String
Dim Counter As Integer
For Counter = 0 To 6
myArray(Counter) = Range("A1").Offset(Counter, 0).Value
Next
End Sub
This is normal: last iteration of the loop increments Counter to 7 and triggers the exit from loop
Counter = 7 ( > 6 )
There are algorithms based on the exit value of the Counter:
Option Explicit
Sub ArrayLoop()
Dim myArray(6) As String
Dim Counter As Integer
For Counter = 0 To 6
myArray(Counter) = Range("A1").Offset(Counter, 0).Value
Next
Do
Debug.Print Counter '---> 7, 6, 5, 4, 3, 2, 1
Counter = Counter - 1
Loop While Counter > 0
Debug.Print Counter '---> 0
End Sub
remember that arrays are zero indexed. So technically the 7th time through the loop it should give you some sort of out of bounds error. Although there is technically nothing wrong with the way you are adding your values to the array.
Also remember that counter increments +1 each time after the loop is completed.
if you wanted it to only use 6 values you would have to change to
For Counter = 0 To 5
myArray(Counter) = Range("A1").Offset(Counter, 0).Value
Next
this would start at 0 the first time through the loop add the value to the array with a 0 index, then increase the index each time +1 and increase the offset by 1 row each time through the loop. And it would only run the loop 6 times.

Math operation with an array but having problems with negative numbers

I got a few arrays and I want to do the following math operation:
For i As Integer = 10 To 100
TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
i = i + 1
Next
The problem is that sometimes mintranArray(i) has higher values than maxFirstArray(i) and maxSecondArray(i). So the program crashes.
With Try Catch the program is not shutting down but I only get TransmissionArray() = Nothing.
Sounds like your TransmissionArray isn't being initialized properly. If you just Dim it like this:
Dim TransmissionArray() As Double
Then it will be Nothing. If you try to assign a value to it in this way, you will get an exception. Normally you can insert a number in the parenthesis (Dim TransmissionArray(10) As Double) and you would have an array of length 10 that you could immediately start assigning values to. But, if you don't know the length before hand, I can think of two options that would work:
Dim TransmissionArray() As Double
For i As Integer = 10 To 100
ReDim Preserve TransmissionArray(i) 'This will increase the size of the array to the value of i, the Preserve keyword also saves the data already stored in the array
TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
'i = i + 1 'Commented this out...i is already incremented once each loop
Next
Or, switch to using a List(Of Double):
Dim TransmissionArray As New List(Of Double)
For i As Integer = 10 To 100
TransmissionArray.Add((maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i)))
'i = i + 1 'Commented this out...i is already incremented once each loop
Next
Note that the second method would make TransmissionArray 10 items less than the other arrays, due to the fact you are starting the For loop counter at 10, and just adding items to the list.

Trouble looping through a data file and storing integers in an array

I am having a problem with a loop. I am writing a program that loops through lottery drawings and does some different analysis' on the drawings. The problem I am having is since a loop is 0-based but there is no number 0 in lottery drawings I cant figure out how to start the loop at 1 instead of 0. Also, when I cut out an integer, if the integer is a single digit the loop doesn't see the zero before the single digit and counts all of the 0-9 in all of the integers. I am trying to grab an integer and then tick that element of the array. Here is the loop.
'Choices(59) is passed into the loop from a click event
Private Sub GetFrequency(Choices() As Integer)
Dim Size As Integer = UsersChosenHistory.Length() 'Size
Dim Number As Integer = 1
Dim Start As Integer = 0
Dim Finish As Integer = 3'Grab 3 chars, a space + 2 digit Integer
For i As Integer = 1 To Size - 1 Step 1
Number.ToString("d2")'I've also tried Number.ToString("D2") (Capitol D)
Number = UsersChosenHistory.Substring(Start, Finish) 'Grab an integer
Choices(Number) += "1" 'Store it in the corresponding array element
Start += 1
Next
End Sub
When running through the loop with the F11 key the single digits do not show the leading "0" even though the data file does include the "0", and as I mentioned above the array shows a "0" as the first digit in the frequence grid. I'm really confused with this loop, any help will be greatly appreciated. I'm just learning VB.Net and this has me stumped. Thanks in advance.
For i As Integer = 0 To Size - 1 Step 1
Number = int.Parse(UsersChosenHistory.Substring(i*3,3).Replace(" ",""))
Choices(Number) += "1"
Next
For the "0" issue, ignore it. Choices(0) will never be incremented.

Resources