您可以按照@norie 的建议使用VALUE 公式,或者您需要更改您的函数,以便它将您从Split 获得的字符串转换为Double 值。
请注意,这不能一次对整个数组进行,您必须转换每个值。这可能比使用VALUE 公式稍慢(在大量数据或广泛使用该函数时)。对于小数据,您不会看到差异。
Option Explicit
Public Function SPLITTER(ByVal Data As String, ByVal Delimiter As String) As Variant()
' split strings
Dim SplittedStrings() As String
SplittedStrings = Split(Data, Delimiter)
' create variant array of the same size (variant so we can return errors)
Dim Values() As Variant
ReDim Values(LBound(SplittedStrings) To UBound(SplittedStrings)) As Variant
' convert each value into double
Dim i As Long
For i = LBound(Values) To UBound(Values)
If IsNumeric(SplittedStrings(i)) Then
' return value as double
Values(i) = CDbl(SplittedStrings(i))
Else
' return #VALUE! error if a value is not numeric
Values(i) = CVErr(xlErrValue)
End If
Next i
SPLITTER = Values
End Function
请注意,返回数组定义为As Variant() 而不是As Double(),因此如果任何拆分的字符串不是数字,它可以为这个值返回一个#VALUE! 错误,并且仍然输出其他值。如果你不这样做,整个函数就会失败,并且会为 all 值输出#VALUE!,即使只有一个无法转换。
由于您无论如何都要重写整个数组,您甚至可以将其带入正确的方向:输出为行或列:
Option Explicit
Public Function SPLITTER(ByVal Data As String, ByVal Delimiter As String, Optional ByVal OutputAsRow As Boolean = False) As Variant()
' split strings
Dim SplittedStrings() As String
SplittedStrings = Split(Data, Delimiter)
' create variant array of the same size (variant so we can return errors)
Dim Values() As Variant
If OutputAsRow Then
' 2-dimensional array with 1 row and n columns
ReDim Values(1 To 1, LBound(SplittedStrings) To UBound(SplittedStrings)) As Variant
Else
' 2-dimensional array with n rows and 1 column
ReDim Values(LBound(SplittedStrings) To UBound(SplittedStrings), 1 To 1) As Variant
End If
' convert each value into double
Dim i As Long
For i = LBound(SplittedStrings) To UBound(SplittedStrings) ' for each value in the input string string
Dim RetVal As Variant
If IsNumeric(SplittedStrings(i)) Then ' check if it is a number
' return value as double
RetVal = CDbl(SplittedStrings(i))
Else
' return #VALUE! error if a value is not numeric
RetVal = CVErr(xlErrValue)
End If
If OutputAsRow Then
Values(1, i) = RetVal ' fill columns
Else
Values(i, 1) = RetVal ' fill rows
End If
Next i
SPLITTER = Values
End Function
所以=SPLITTER($A$1,";") 或=SPLITTER($A$1,";",0) 会将其输出为列,=SPLITTER($A$1,";",1) 将输出为行。