在vba中将数组向下移一位

我有一些麻烦,得到一个函数,我一直在写正常工作。 我需要它将大小为1到x的数组,并将其转移到一个新的数组,大小为0到x-1。 我会认为它会像这样工作:

Private Function ShiftDownArray(theArray() As String) As String() Dim a As Integer ReDim ShiftDownArray(LBound(theArray) - 1 To UBound(theArray) - 1) For a = LBound(theArray) To UBound(theArray) ShiftDownArray(a - 1) = theArray(a) Next a End Function 

但是我得到一个编译错误:赋值左侧的函数调用必须返回Variant或Object。 关于这个错误的文档基本上说,删除该行,使其工作,这并没有指向我在正确的方向。 我已经尝试将types更改为变体,但它启动了需要将数组types从string更改为变体的连锁反应,并导致我的程序的其他部分出现问题。

有什么办法可以让我保留string数组types吗? 谢谢

这是你想要的:

 Public Sub ShiftArrayTest() 'Make an 1-bound array Dim arr1() As String, N As Long, i As Long N = 10 ReDim arr1(1 To N) For i = 1 To N arr1(i) = CStr(i) Next i 'Now for the shift Dim arr2() As String arr2 = ShiftArray(arr1) End Sub Public Function ShiftArray(ByRef theArray() As String) As String() 'Now for the shift Dim i1 As Long, N As Long, i As Long, res() As String i1 = LBound(theArray): N = UBound(theArray) - i1 + 1 ReDim res(0 To N - 1) For i = 0 To N - 1 res(i) = theArray(i1 + i) Next i ShiftArray = res End Function 

我在这里做的是采取任何数组,并将其转换为0绑定数组。

您可以将大部分types的数组作为VBA中的方法和过程之间的Variant传递

 Private Function ShiftDownArray(ByRef theArray As Variant) As Variant Dim i As Integer ReDim x(0 To UBound(theArray) - 1) As Variant For i = 0 To UBound(x) x(i) = theArray(i + 1) Next i ShiftDownArray = x End Function 

但更重要的是,你为什么要这样做呢? 你可以 – / + 1到原始数组中的索引?

错误是最有可能在这一行:'ReDim ShiftDownArray(LBound(theArray) – 1到UBound(theArray) – 1)'

它看起来像你recursion调用自己,这似乎是奇怪的,因为没有一个基本的情况下。

请参阅本网站提供的以下示例。 它的要点是它会跳过第一个元素,并将所有内容复制到“左侧”。

 Function Array_Shift(arr As Variant) As Variant ' http://www.php.net/manual/en/function.array-shift.php Dim tempArray As Variant Dim i As Long tempArray = arr ' shift elements one position up ' by skipping the first element of the source array For i = LBound(tempArray) To UBound(tempArray) - 1 tempArray(i) = tempArray(i + 1) Next i ' remove last element ' which is now empty ReDim Preserve tempArray(LBound(tempArray) To UBound(tempArray) - 1) Array_Shift = tempArray End Function 

问题不在于传递一个string数组作为参数 – 您可以传递任何types的数组,只要我知道。 但是,为ShiftDownArray(a - 1)赋值是不明确的,因为您可能正在访问数组的第1个元素,或者将a - 1作为parameter passing给ShiftDownArray()函数。

Function call on left-hand side of assignment must return Variant or Object.Function call on left-hand side of assignment must return Variant or Object. 错误信息提示。 您正在调用ShiftDownArray()函数而不是访问数组。 编译器知道你要分配一些东西给函数返回的值(因为它后面跟着一个= ),但不知道types,因为它还没有评估过theArray(a) 。 为了确保赋值可以完成而不pipetheArray(a)的types如何,编译器会尝试确保ShiftDownArray()返回一个Variant或者Object来指定任何东西。

为了避免这个错误,你可以创build一个临时数组,这个数组可以以传统方式访问,并将该数组分配给ShiftDownArray以从函数返回。

以下代码显示了这一点:

 Private Function ShiftDownArray(theArray() As String) As String() ReDim tempArray(LBound(theArray) - 1 To UBound(theArray) - 1) As String Dim i As Integer For i = LBound(tempArray) To UBound(tempArray) tempArray(i) = theArray(i + 1) Next i ShiftDownArray = tempArray End Function