|
-
May 4th, 2003, 12:01 PM
#1
Thread Starter
Lively Member
Array(s) Resolved
Hi everyone ...
brand new to this forum and just learning vb/vba.
In Excel, i am trying to write a function.
I have several named ranges and have figured out how to loop through the ranges and get a total of all cells in all ranges.
Now what I am trying to figure out is ...
I want to create 4 arrays. 1 for each named range in this spreadsheet(all the ranges are different lenghts and will be added to often). I then want to loop through each range and assign each cells value to one element of the array, reDim and Preserve the array, then get the next value. Once I have all the elements, I can (hopefully) perform some calculations based on certain criteria.
I am calling the function from a command button click event.
Any help, ideas, or direction to examples is appreciated.
Thanks
Last edited by IGBP; May 16th, 2003 at 09:10 AM.
-
May 5th, 2003, 08:45 PM
#2
Fanatic Member
To assign the values to an array, you need to Dim the array variable with parentheses () with nothing in them. That lets VB know the variable is an array but doesn't have a fixed number of elements. You must ReDim the array with the low-bound value before you can use it. As you loop through the cells in the range, ReDim Perserve the array, incrementing the the upper-bound index by one. Here's a funtion:
VB Code:
Function RangeToArray(ByVal strRangeName As String)
Dim c As Range
Dim ReturnArray()
ReDim ReturnArray(0)
For Each c In Range(strRangeName)
ReDim Preserve ReturnArray(UBound(ReturnArray) + 1)
ReturnArray(UBound(ReturnArray)) = c.Value
Next
RangeToArray = ReturnArray
End Function
You can call it like this:
VB Code:
Sub MyClickEvent()
Dim i As Long
Dim MyRangeValues()
ReDim MyRangeValues(0)
MyRangeValues = RangeToArray("MyRangeName")
For i = 1 To UBound(MyRangeValues)
Debug.Print MyRangeValues(i)
Next
End Sub
If you want, you can use another variable in the Function to keep track of incrementing the upper-bound index of the array instead of checking the UBound each time.
-
May 6th, 2003, 10:46 AM
#3
Thread Starter
Lively Member
WorkHorse,
Excellent Post. Thank-you very much.
I will try it and let you know.
IGBP
-
May 9th, 2003, 09:17 AM
#4
Thread Starter
Lively Member
Resolved
Thanks WorkHorse
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|