[英]Excel VBA Array Function that will shift a Vector up
I need an array function that will shift up a vector at rng range by n cells.我需要一个数组函数,它将在 rng 范围内将向量上移 n 个单元格。 Here is my code so far:
到目前为止,这是我的代码:
Option Explicit
Option Base 1
Function ShiftVector(rng As Range, n As Integer)
Dim nr As Integer
Dim i As Integer
Dim head() As Variant
Dim tail() As Variant
Dim shift() As Variant
nr = rng.Rows.Count
ReDim head(n)
For i = 1 To n
head(i) = rng(i).Value
Next i
ReDim tail(nr - n)
For i = 1 To nr - n
tail(i) = rng(n + i).Value
Next i
ReDim shift(nr)
For i = 1 To nr - n
shift(i) = tail(i)
Next i
For i = (nr - n + 1) To nr
shift(i) = head(i - (nr - n))
Next i
ShiftVector = shift()
End Function
I have tested running this as a subroutine and saw that in the locals window the new array "shift()" had the values I needed, however I am having trouble outputting the new array as a function in a new location show below:我已经测试过将此作为子例程运行,并在本地窗口中看到新数组“shift()”具有我需要的值,但是我无法将新数组作为函数输出到新位置,如下所示:
When dealing with Ranges its easiest to work 2D Arrays.在处理范围时,最容易使用 2D 数组。 Also, your logic can be simplified quite a bit.
此外,您的逻辑可以简化很多。
Function ShiftVector(rng As Range, n As Long)
Dim i As Long
Dim shift() As Variant
Dim dat As Variant
ReDim shift(1 To rng.Rows.Count, 1 To 1)
dat = rng.Value 'this will speed up the UDF on larger ranges
For i = 1 To n
shift(i, 1) = dat(i + n, 1)
Next i
For i = n + 1 To rng.Rows.Count
shift(i, 1) = dat(i - n, 1)
Next i
ShiftVector = shift()
End Function
I'd also suggest adding some range checks on n
and size/shape checks on rng
我还建议在
n
上添加一些范围检查,并在rng
上添加一些大小/形状检查
FWIW your code could be fixed by changing the last line to ShiftVector = Application.Transpose(shift())
FWIW 可以通过将最后一行更改为
ShiftVector = Application.Transpose(shift())
来修复您的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.