英文:
how to check if Split()result is valid?
问题
我有一个名为LastItem
的函数,它返回字符串中的最后一个单词。对于具有值的字符串,它运行正常,但对于空白字符串如"",它会失败。
我正在检查Split函数是否返回一个数组。即使对于空白字符串,IsArray()也会返回true。有没有修复的方法。
错误在代码中作为注释提到。
Sub test()
Debug.Print LastItem("a b c")
Debug.Print LastItem("a")
Debug.Print LastItem("") '''' ===>> 对于这个会出错
End Sub
Public Function LastItem(source As String) As String
Dim arr
arr = Split(source, Space(1))
If IsArray(arr) Then
LastItem = arr(UBound(arr)) '''' ===>> 对于 LastItem("") 错误是 [Subscript out of range]
Else
LastItem = source
End If
End Function
英文:
I have a function LastItem
which returns the last word from the string. It works fine for strings with value but for blanks like "" it fails.
I am checking if Split returned an Array. Even for blank string the IsArray() returns true. Is there a way to Fix it.
Errors are mentioned as comment in the code.
Sub test()
Debug.Print LastItem("a b c")
Debug.Print LastItem("a")
Debug.Print LastItem("") '''' ===> Error for this one
End Sub
Public Function LastItem(source As String) As String
Dim arr
arr = Split(source, Space(1))
If IsArray(arr) Then
LastItem = arr(UBound(arr)) '''' ===> For LastItem("") error is [Subscript out of range]
Else
LastItem = source
End If
End Function
答案1
得分: 3
检查上限是否大于-1
Public Function LastItem(source As String) As String
Dim arr
arr = Split(source, Space(1))
'/ 检查上限是否大于-1
If UBound(arr) > -1 Then
LastItem = arr(UBound(arr))
Else
LastItem = source
End If
End Function
英文:
Check if upper bound is greater than -1
Public Function LastItem(source As String) As String
Dim arr
arr = Split(source, Space(1))
'/ Check if upper bound is greater than -1
If UBound(arr) > -1 Then
LastItem = arr(UBound(arr))
Else
LastItem = source
End If
End Function
答案2
得分: 2
Split
始终返回一个数组,因此不需要进行IsArray
检查。
如果输入是零长度字符串,那么可以尽早退出。
Public Function LastItem(source As String) As String
If source = vbNullString Then Exit Function
Dim arr
arr = Split(source, Space(1))
LastItem = arr(UBound(arr))
End Function
英文:
Split
always returns an array so an IsArray
check is unnecessary.
How about this? Bail early if the input is a zero-length string.
Public Function LastItem(source As String) As String
If source = vbNullString Then Exit Function
Dim arr
arr = Split(source, Space(1))
LastItem = arr(UBound(arr))
End Function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论