PDA

View Full Version : Sum of Array Using Sub procedure and Function



vaibhav88
11-05-2011, 06:15 PM
Hello to all of you, I am Vaibhav Chauhan Masters Student at Lamar University I am new to programming hence I am working on my programming skills so that it will help me to understand the basic concepts of Heuristics.and as an exercise I wrote following code in my VBA module window but in the cell("a1") every time the answer is 5050,with this code I aim to get the sum of random numbers generated, Pls help and I would really appreciate for all the inputs provided by you guys but spare me of my errors as I am new to programming :)


Option Base 1
Function sumarray(x) As Double
sumarray = 0
For i = 1 To 100
sumarray = sumarray + i
Next i
End Function
Sub genarray()
Dim i(100) As Double
For ak = 1 To 100
a = Int((Rnd() * 100))
i(ak) = a
Next ak
Worksheets(1).Range("a1").Value = sumarray(i)
End Sub



Vaibhav Chauhan
s/w used EXCEl 2003

mikerickson
11-05-2011, 07:00 PM
In the sumarray function, you are not referencing the array argument that was passed. You are only summing the indexes. That is why it is returning the sum 1+2+3+...100.

Changing this line should set things right
sumarray = sumarray + x(i)

vaibhav88
11-05-2011, 08:13 PM
Thank-you very much for helping me to understand the concepts.I really appreciate your help.

Vaibhav Chauhan

mdmackillop
11-06-2011, 02:31 PM
Always use Option Explicit and declare your variables.
This expands your code a little to demonstrate a couple of concepts

Option Explicit
Option Base 1

Sub genarray()
Dim i() As Long
Dim ak As Long, a As Long
Dim x As Long

x = 100

ReDim i(x)

For ak = 1 To x
a = Int((Rnd() * 100))
i(ak) = a
Next ak

Worksheets(1).Range("a1").Value = SumArray(i)
End Sub

Function SumArray(Arr) As Double
Dim i As Long, j As Double
For i = 1 To UBound(Arr)
j = j + Arr(i)
Next i
SumArray = j
End Function

vaibhav88
11-06-2011, 04:11 PM
I really appreciate your help because all the inputs that have been provided till now have increased my ken of programming and VBA as well.

Thank-you
Vaibhav Chauhan