Redimension and paste dynamic ranges in VBA
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 ra开发者_如何学编程nge 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
If you use the Preserve keyword, you can resize only the last array dimension
...while you are trying to ReDim Preserve
the first dimension. Besides, ReDim Preserve
is 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, just ReDim
it 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:
Dim nVal As Long
nVal = WorksheetFunction.CountA(rangeTimeValue.Columns(1))
ReDim outputRange(1 To nVal, 1 To 2)
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 outputRange
array somewhere on your sheet, then this is how you could do it:
Dim rngOutput As Range
Set rngOutput = Sheet1.Range("G12") ' or wherever
rngOutput.Resize(UBound(outputRange, 1), UBound(outputRange, 2)) _
= outputRange
By the way, outputRange
is a pretty terrible name for your array. It's not a Range
, so this name can lead to confusion, and I think it has indeed done so for you. Why not call it e.g. varOutput
instead, since it's a Variant
array.
精彩评论