函数在返回数组数组时给出Value错误



我正试图在Excel中创建一个可以接受单个引用或范围的TextSplit函数
如果是单个字符串,则返回子字符串数组
如果是一个范围,则应返回一个子字符串数组的数组。

一个字符串有效,但当我给它传递一个单列范围时,它会给我一个#VALUE!错误

注释行有效
如果我将Array的结果存储到arr Excel中;测试";字符串
如果我将TextSplit设置为仅arr(1(,我将获得类似于单个字符串版本的单个子字符串数组。

Function TextSplit(text, delimiter)
If IsArray(text) Then
Dim arr() As Variant: ReDim arr(0 To text.Count - 1)
For i = 1 To text.Count
arr(i-1) = Split(text(i), delimiter)
'arr(i-1) = Array("test", "test")
Next
TextSplit = arr
'TextSplit = arr(1)
Else
TextSplit = Split(text, delimiter)
End If

借助不同问题的Array和Split命令创建二维数组

我可以稍微解决你的问题,但我仍然无法从你调用函数的单元格中填充数组,就像用一个字符串填充它旁边的列一样。如果是一列,你可以在Excel中自动填充文本。split(单元格,分隔符(。

如果你正在使用vba,并想将分割数组(如@Tim所说的2D(返回到sub:

Sub testingTextSplitter()
Dim arr As Variant, tArr As Variant
Dim testStr As String

testStr = Range("A1").Value 'Testing single cell
Range("G2").Value = TextSplit(testStr, "-")
arr = Range("A1:A8").Value
tArr = TextSplit(arr, "-")
For i = 0 To UBound(tArr, 1)
For j = 0 To UBound(tArr, 2)
Cells(i + 3, j + 3).Value = "'" & tArr(i, j) 'fills out from Range("C3"), adjust as needed
' This writing out is basically the same as fillingdown the formule of text.split() btw
Next j
Next i

End Sub

具有功能

Function TextSplit(tArray As Variant, delimiter As String) As String()
If IsArray(tArray) Then
Dim uBoundInput As Long, uBoundCells As Long 'I couldn't get your arr.Count to work on my end so gotta use the UBound
Dim arr() As String, testArr() As String
Dim i As Long, j As Long, maxColumns As Long

uBoundInput = UBound(tArray)

maxColumns = 0
For i = 0 To uBoundInput - 1
Debug.Print (tArray(i + 1, 1))
testArr = Split(tArray(i + 1, 1), "-")
uBoundCells = UBound(testArr)
If maxColumns < uBoundCells Then
maxColumns = uBoundCells
End If
Next i

ReDim arr(0 To uBoundInput - 1, 0 To maxColumns)

For i = 0 To uBoundInput - 1
testArr = Split(tArray(i + 1, 1), "-")
For j = 0 To UBound(testArr)
arr(i, j) = testArr(j)
Next j
Next i
TextSplit = arr()
Else
TextSplit = Split(tArray, delimiter)
End If
End Function

我对VBA也很陌生,所以提前为冗余道歉,比如在计算maxColumns时没有填充testArray,我无法计算出来。第一次使用2D阵列。

其他可能有帮助的问题:VBA UDF返回数组(我尝试使用{}的数组公式,但得到了与以前相同的值错误(

希望这能有所帮助。

我不知道发生了什么,但我的代码的数组分支现在正在工作。我一直在搞一些事情,但我不确定为什么它能起作用。";作为变量((";声明是上面代码中的新声明,但以前可能已经省略了。(这个代码在我的工作机器上,但我是在我的个人电脑上写的原始帖子,所以我不能复制和粘贴。我现在在我的办公电脑上。(

我所做的唯一其他更改是对arr数组的索引值。

谢谢你的帮助,但不确定出了什么问题或是如何解决的。

Function TextSplit(text, delimiter) As Variant()
If IsArray(text) Then
Dim arr() As Variant: ReDim arr(1 To text.Count)
For i = 1 To text.Count
arr(i) = Split(text(i), delimiter, -1, 1)
Next
TextSplit = arr
Else
TextSplit = Split(text, delimiter, -1, 1)
End If
End Function

最新更新