我试图从excel单元格中指定的名称中获取除最后一个之外的所有单词。出于某种原因,我的简单VBA代码将无法运行;它只是给我原来的名字。有人可以帮忙解释一下原因吗?
npm run-script ng
答案 0 :(得分:3)
您将整个数组包含在输出中 - 您需要在最后一个元素之前停止...
此外,您发布的代码不会返回任何值
Function GetName(Source As String)
Dim arr() As String 'declares a dynamic array
arr = VBA.Split(Source, " ") 'an array of words split by space from the Source string is built
'Ubound function gets the last position of items in the array
GetName = ""
For i = LBound(arr) To UBound(arr) - 1 '<<<<<<<<<<<<<
GetName = GetName + " " + arr(i)
Next i
End Function
替代方法:
Function GetName(Source As String) As String
Dim arr, v
v = Trim(Source)
If Len(v) > 0 Then
arr = VBA.Split(v, " ")
If UBound(arr) - LBound(arr) > 0 Then
ReDim Preserve arr(LBound(arr) To UBound(arr) - 1) '<< remove last element
GetName = Join(arr, " ")
Else
GetName = v
End If
End If
End Function