Function with array returning 0 Visual Basic - arrays

I'm quite new at using arrays and functions in Visual Basic and I cannot seem to figure this out. My problem is that whenever I call the function Fibo it returns 0 no matter the value of n I give it. I'm sure the error is pretty basic.
Any pointer would be really appreciated!
Public Function fibo(n As Integer) As Integer
Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci
arrayFib(0) = 0 'idem
arrayFib(1) = 1 'declare start value
Dim i As Integer = 2 'start position
While i <= n
arrayFib(i) = arrayFib(i - 1) + arrayFib(i - 2)
i = 1 + i
Return arrayFib(i)

Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci
We can sort of guess where that +1 came from. You added it because your original code crashed with an IndexOutOfRangeException. Caused by you returning arrayFib(i), i was incremented to be larger than n, its value is n+1 after the loop. And thus returns the value of an element that was never assigned. You didn't fix it correctly :)
Fix the array declaration back the way it was and return arrayFib(n) instead.

Related

VBA UDF multiple array arguments

I am trying to make a UDF in VBA that takes multiple arrays of equal size as an argument and then loops through them staying at the same index for each array.
I have set the code up as follows.
Public Function TwoArrays(TargetRange(), CriteriaRange())
dim value as range
for each value in TargetRange
next
end function
The issue is I can't get the index of the TargetRange to use in the CriteriaRange and even if I could for whatever reason whenever I put something like
CriteriaRange(2)
I get an error instead of what happens to be within that index.
Is there a way I can get the UDF to treat the array like a normal VBA array where I can do something along the lines of
Public Function TwoArrays(TargetRange(), CriteriaRange())
dim result as range
for i = lowerbound(TargetRange) to ubound(TargetRange)
If CriteriaRange(i) > 0 then
result = result + TargetRange(i)
end if
next i
end function
Thank you!
Like this:
Public Function TwoArrays(TargetRange As Range, CriteriaRange As Range)
Dim result, arrT, arrC, r As Long, c As Long
arrT = TargetRange.Value
arrC = CriteriaRange.Value
'probably should add some code here to check both ranges are the same size...
For r = 1 To UBound(arrT, 1)
For c = 1 To UBound(arrT, 2)
If arrC(r, c) > 0 Then result = result + arrT(r, c)
Next c
Next r
TwoArrays = result
End Function

How do I remove all null or empty elements from my array in vb.net?

The code block computes two values for speeds; Vsf and Vro using their corresponding parameter values: Angle, Super-elevation and Radius for each iteration of the for- loop statement. During each loop, it selects the minimum of both speed values. In some scenario's, Angle, super-elevation but most of all, Radius are all null values, leading to Vsf and Vro values of null and hence Vmin of null. I want to eliminate these scenarios and produce just non-zero values for Vmin hence my question.
For i = 1 To CInt(txtNumSections.Text)
ReDim Preserve Vsf(i)
ReDim Preserve Vro(i)
ReDim Preserve Vmin(i)
Vsf(i) = (((0.91544 - 0.00166 * Angle(i) - 0.000002 * W - 0.054248 * Superelevation(i) - Sidefrictionfactor) / 0.013939) * Radius(i)) ^ 0.5
Vro(i) = (((1.05653 - 0.004861 * Angle(i) - 0.000004 * W - 0.314653 * Superelevation(i) - rolloverthreshold) / 0.012729) * Radius(i)) ^ 0.5
Vmin(i) = Math.Min(Vsf(i), Vro(i))
If Vmin(i) <= "0" Then
Vmin(i) = "0"
End If
Next
Dim myList = New List(Of Double)
For Each s In Vmin
If Not String.IsNullOrWhiteSpace(s) Then
myList.Add(s)
End If
Next
Vmin = myList.ToArray()
Since arrays are immutable(you can't add or remove items) you can just re-create it:
myArray = myArray.Where(Function(s) Not String.IsNullOrEmpty(s)).ToArray()
This is a String() but this LINQ query works similar with any other type of array.
A non-LINQ appproach would be to fill a List(of T) and then use ToArray:
Dim myList = New List(Of String)
For Each s In myArray
If Not String.IsNullOrEmpty(s)
myList.Add(s)
End If
Next
myArray = myList.ToArray()
You see that LINQ can make your code more readable and understandable.
Alright guys, I found a workaround this, based on the purpose of the code piece. I simply set all null or negative values to the maximum allowable values. There's some context to it which makes it a sensible approach but I would need to explain the entire operation of the code block which I'm not sure you would have any interest in. Anyway, thanks for your contributions. They are very much appreciated

How to Pass an Array to and from a Function?

(Fair Warning, I am self taught on VBA so I apologize in advance for any cringe-worthy coding or notations.)
I have an estimating worksheet in excel. The worksheet will have a section for the user to input variables (which will be an array). The first input variable will "reset" the remaining input variables to a standard value when the first variable is changed. The standard values for the input variables are stored in a function in a module. I am attempting to fill the input variable array with the standard values from the function and then display those values on the sheet. I was easily able to do this without arrays but have had no luck in moving everything into arrays.
This is for excel 2010. I previously did not use arrays and created a new variable when needed, however the estimating sheet has grown much larger and it would be better to use arrays at this point. I have googled this question quite a bit, played around with removing and adding parenthesis, changing the type to Variant, trying to set the input variable array to be a variable that is an array (if that makes sense?), and briefly looked into ParamArray but that does not seem applicable here.
Dim BearingDim(1 To 9, 1 To 4, 1 To 8) As Range
Dim arrBearingGeneral(1 To 5, 1 To 8) As Range
Dim Test As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
'Set General Variable array to cells on the worksheet
For i = 1 To 5
For j = 1 To 8
Set arrBearingGeneral(i, j) = Cells(9 + i, 3 + j)
Next j
Next i
'Set Bearing Input Variables to Cells on the Worksheet
For p = 1 To 4
For i = 1 To 9
Select Case p
Case Is = 1
Set BearingDim(i, p, 1) = Cells(16 + i, 4)
Case Is = 2
Set BearingDim(i, p, 1) = Cells(27 + i, 4)
Case Is = 3
Set BearingDim(i, p, 1) = Cells(37 + i, 4)
Case Is = 4
Set BearingDim(i, p, 1) = Cells(49 + i, 4)
End Select
Next i
Next p
'Autopopulate standard input variables based on Bearing Type
inputMD_StdRocker BearingType:=arrBearingGeneral(1, 1), _
arrBearingDim:=BearingDim
End Sub
Sub inputMD_StdRocker(ByVal BearingType As String, ByRef _
arrBearingDim() As Variant)
Dim arrBearingDim(1 To 9, 1 To 4)
Select Case BearingType
Case Is = "MF50-I"
For j = 1 To 2
arrBearingDim(2, j) = 20
arrBearingDim(3, j) = 9
arrBearingDim(4, j) = 1.75
Next j
arrBearingDim(5, 1) = 15
'There are numerous more select case, but those were removed to keep it
'short
End Select
End Sub
The expected output is my "BearingDim" Array will have certain array index values set to a standard value from the "inputMD_StdRocker" function. Then those values will be displayed in the cell that corresponds to the array index.
Currently, I get a compile error "Type Mismatch, Array or User-Defined Type Expected". I have been able to get around the type mismatch by removing the () from "arrBearingDim()" in the function title for "inputMD_StdRocker" however, it will not pass the values back to my "BearingDim" array.
Any help would be greatly appreciated.
This is a partial answer to what (I think) is a misunderstanding you have of how to use arrays. There are a few problems in your code.
First, you're defining a two-dimensional and a three-dimensional array of Ranges when I believe you really only want to store the values captured from the worksheet. (If I'm wrong, then you are never initializing the array of Ranges, so none of the ranges in the array actually point to anything.)
Secondly, it looks as if your initial array arrBearingGeneral is always filled from the same (static) area of the worksheet. If this is so (and you really do want the values from the cells, not an array of Range objects), then you can create a memory-based array (read this website, especially section 19). So the first part of your code can be reduced to
'--- create and populate a memory-based array
Dim bearingDataArea As Range
Dim arrBearingGeneral(1 To 5, 1 To 8) As Variant
Set bearingDataArea = ThisWorkbook.Sheets("Sheet1").Range("D10:K14")
arrBearingGeneral = bearingDataArea.Value
Optionally of course you can calculate the range of your data instead of hard-coding it ("D10:K14"), but this example follows your own example.
While this isn't a complete answer, hopefully it clears up an issue to get you farther down the road.

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.

Finding the mean using a function. vb.net

I'd firstly like to say I'm a beginner in vb.net and coding in general.
I'm trying to find the mean of the numbers in an array.
So far, my code is this.
Function getMean() As Double
Dim DblArray(lstbxInput.Items.Count - 1) As Double
Dim totalsum As Double
Dim i As Integer
For i = 0 To dblArray.Length - 1
totalsum += DblArray(i)
Next i
dblmean = totalsum / DblArray.Length
Return dblmean
End Function
In the end, I need for dblmean to return the mean value of the dblarray numbers.
Would this be correct?
Well obviously it's wrong because I tried to print the value on a label and it always comes out as zero. Why?
Is there something wrong with the code? or was there something wrong in printing out the value?
Also, this is the code used to print out dblmean
lblLrgAns.Text = dblmean.ToString
it happens when i click a button.
A simple approach is to use the Enumerable.Average extension method which is sitting in the System.Linq namepsorts(so remember to add the Import).
Dim mean As Double = DblArray.Average()
In your case you need to initialize the array first. I guess the items in lstbxInput are already doubles.
Dim DblArrayAs As Double() = lstbxInput.Items.Cast(Of Double)().ToArray()
When you do this
Dim DblArray(lstbxInput.Items.Count - 1) As Double
All of DblArray items are 0, but you never change any of the DblArray items in your code, so dblmean would also be 0. You need to assign each item of DblArray before calculating the mean.
I would guess this is related to your previous question: putting a list into an array?, so here's how your code should look like
Function getMean() As Double
Dim DblArray(lstbxInput.Items.Count - 1) As Double
'get the items from lstbxInput
getNumbers(DblArray)
Dim totalsum As Double
Dim i As Integer
For i = 0 To dblArray.Length - 1
totalsum += DblArray(i)
Next i
dblmean = totalsum / DblArray.Length
Return dblmean
End Function

Resources