我在编写正在编写的函数时遇到了一些麻烦。我需要它来获取一个大小为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。关于这个错误的文档基本上是说删除该行以使其工作,这并没有指向正确的方向。我已经尝试将类型更改为variant,但它启动了需要将数组类型从字符串更改为变量的连锁反应,并且它会导致程序其他部分出现问题。
有没有办法解决这个问题,这样我才能保留字符串数组类型?感谢
答案 0 :(得分:1)
您可以在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到原始数组中的索引吗?
答案 1 :(得分:0)
错误很可能就在这一行:' ReDim ShiftDownArray(LBound(theArray) - 1到UBound(theArray) - 1)'
看起来你已经递归地调用了自己,这似乎很奇怪,因为没有基本情况。
请参阅此website提供的以下示例。它的要点是它将跳过第一个元素并将所有内容复制到左侧'。
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
答案 2 :(得分:0)
这就是你要找的东西:
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绑定数组。
答案 3 :(得分:-1)
问题不在于将字符串数组作为参数传递 - 据我所知,您可以传递任何类型的数组。但是,为ShiftDownArray(a - 1)
指定值是不明确的,因为您可以访问数组的第1个元素或将a - 1
作为参数传递给ShiftDownArray()
函数。
Function call on left-hand side of assignment must return Variant or Object.
错误消息提示此。您正在调用ShiftDownArray()
函数而不是访问该数组。编译器知道你要为函数返回的值赋值(因为后跟=
),但不知道类型,因为它还没有评估theArray(a)
。为了确保无论theArray(a)
的类型如何都可以完成分配,编译器会尝试确保ShiftDownArray()
返回可以分配任何内容的Variant
或Object
。
为避免此错误,您可以创建一个临时数组,可以按常规方式访问该数组,并将该数组分配给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