i’m new to VBA and I’m having problems with arrays and ranges. I have to write a function to select portions of a range made of values with a time stamp and report them in a separate range.
The range is like this one:
A B
1 15-May-11 23:47:40 False
2 15-May-11 23:49:10 False
3 15-May-11 23:49:10 False
4 15-May-11 23:50:52 True
5 15-May-11 23:50:52 False
6 15-May-11 23:51:56 False
7 15-May-11 23:51:56 True
8 15-May-11 23:53:24 False
9 15-May-11 23:53:24 False
and I have prepared this function:
Function selectEvents(rangeTimeValue, Val As String)
Dim outputRange() As Variant
j = 1
For i = 1 To rangeTimeValue.Height
Val_recorded = rangeTimeValue(i, 2).Value
Time_recorded = rangeTimeValue(i, 1).Value
If Val_recorded = Val Then
ReDim Preserve outputRange(j, 2) '(1)
outputRange(j, 1) = Time_recorded
outputRange(j, 2) = Val_recorded
j = j + 1
End If
Next i
selectEvents = Application.Transpose(outputRange) '(2)
End Function
now, there are two problems:
- the function breaks when the array
is re-dimensioned the second time
(1) - I have an error also when
pasting the results (2) because the
range should be defined before I
guess, but I don’t manage to find a
way to pass the range’s dimension in
a parametric way
I would be grateful of any help, Thanks!
1. ReDim Preserve
Quoting from VBA help
…while you are trying to
ReDim Preservethe first dimension. Besides,ReDim Preserveis an expensive operation and you should avoid it unless it’s absolutely necessary, which it isn’t in your case. Since you can figure out the maximum number of elements your array will contain, justReDimit once at the top of your code.Also, it is good practice to specify the lower bounds of your array explicitly, rather than just let them be whatever the default is and hope for the best.
Example of how to do both these things:
2. “Pasting” the results
I’m not sure what you mean here, because you’re not pasting anything anywhere. Is this a typo where you meant pas*s*ing? Or do you mean transposing? I can’t figure out what you’re trying to do on that line with
.Transpose. I don’t know. I’ll just take a stab in the dark:If you want to place the contents of your
outputRangearray somewhere on your sheet, then this is how you could do it:By the way,
outputRangeis a pretty terrible name for your array. It’s not aRange, so this name can lead to confusion, and I think it has indeed done so for you. Why not call it e.g.varOutputinstead, since it’s aVariantarray.