Excell单元格值不读为Number?

时间:2016-07-25 20:05:51

标签: excel vba excel-vba

我正在尝试在Excel工作表的两个单元格中添加数据,但即使excel单元格的类型编号也不会添加单元格。似乎没有添加的数字的空间信息....图像在下面。 是否有vba代码可以从每个单元格中删除此空格。enter image description here

我已从pdf中导出excel。

1 个答案:

答案 0 :(得分:0)

如果您对其应用运算符,Excel将尝试将任何值转换为数字,并且此转换将处理空格。因此,您可以使用=A1*1A1+0将A1中的值转换为函数=SUM(IFERROR(A1*1,0))中的数字或类似内容。

这种隐式转换会自动执行trim()。您也可以使用功能N()NumberValue() for newer versions of Excel明确执行此转换。但是,正如其他人指出的那样,许多字符不会被自动处理,您可能需要使用Substitute()来删除它们。例如,non-breaking space, a prime suspect because of its prevalence in htmlSubstitute(A1,160,"")Clean()函数可以为一堆已知有问题的字符提供快捷方式,但它并不全面,您仍然需要为不间断的空间添加自己的处理。您可以使用Code()函数找到让您感到悲伤的任何特定字符的ASCII代码...例如Code(Mid(A1,1,1))

字符处理UDF

下面的UDF通过允许从范围中的每个单元格中删除多个字符来提供字符处理方法的灵活性,并生成可用作参数的结果。例如,Sum(RemoveChar(A1:A5,160))将从被求和的范围中删除所有非中断空格。可以通过在范围或数组中指定来删除多个字符,例如Sum(RemoveChar(A1:A5,B1:B3))Sum(RemoveChar(A1:A5,{160,150}))

Function RemoveChar(R As Range, ParamArray ChVal() As Variant)
    Dim x As Variant
    Dim ResVals() As Variant
    ReDim ResVals(1 To R.Count)
    'Loop through range
    For j = 1 To R.Count
        x = R(j).Value2
        If x <> Empty Then
            'Try treating character argument as array
            'If that fails, then try treating as Range
            On Error Resume Next
            For i = 1 To UBound(ChVal(0))
                x = Replace(x, Chr(ChVal(0)(i)), "")
            Next
            If Err = 92 Then
                Err.Clear
                For Each Rng In ChVal(0)
                    x = Replace(x, Chr(Rng.Value2), "")
                Next
            End If
            Err.Raise (Err)
            On Error GoTo 0
            'If numeric then convert to number
            'so that numbers will be treated as such
            'when array is passed as an argument
            If IsNumeric(x) Then
                ResVals(j) = Val(x)
            Else
                ResVals(j) = x
            End If
        End If
    Next
    'Return array of type variant
    RemoveChar = ResVals
End Function

数字验证UDF

替换字符的缺点是它不全面。如果你想要一些更具吸引力的东西,那么也许就是这样。

Function GetNumValues(R As Range)
    Dim c, temp As String
    Dim NumVals() As Double
    ReDim NumVals(1 To R.Count)
    'Loop through range
    For j = 1 To R.Count
        'Loop through characters
        'Allow for initial short-circuit if already numeric
        For i = 1 To Len(R(j).Value2)
            c = Mid(R(j).Value2, i, 1)
            'If character is valid for number then include in temp string
            If IsNumeric(c) Or c = Application.DecimalSeparator Or c = Application.ThousandsSeparator Then
               temp = temp + c
            End If
        Next
        'Assign temp string to array of type double
        'Use Val() function to convert string to number
        NumVals(j) = Val(temp)
        'Reset temp string
        temp = Empty
    Next
    'Return array of type double
    GetNumValues = NumVals
End Function