功能'权利'

时间:2018-03-22 10:01:00

标签: excel vba excel-vba excel-formula

我尝试将函数Right的输出转换为整数。我对Left做了同样的事情并且工作得非常好:

Public Function LEFT_NUM(cv As String, ch As Long)

cv = CStr(cv)
output = Left(cv, ch)

check = IsNumeric(output)

If check = True Then
    LEFT_NUM = CInt(output)
Else
    LEFT_NUM = output
End If

这不起作用:

Public Function RIGHT_NUM(cv As String, ch As Long)

cv = CStr(cv)
output = Right(cv, ch)

check = IsNumeric(output)

If check = True Then
    RIGHT_NUM = CInt(output)
Else
    RIGHT_NUM = output
End If

End Function

编辑:如果单元格的值为12345(仅限数字),则会返回#VALUE错误。如果单元格的值是12345abc,则返回该字符串的一部分。问题是,当单元格中只有数字时,它不起作用。

当我尝试通过RIGHT_NUM(A1; 5)和LEFT_NUM(A1; 6)接收超过4位数字(仅限数字的单元格)时出现错误。

任何想法为什么?

1 个答案:

答案 0 :(得分:0)

从评论中摘录

答案由Chronocidal提供

CInt更改为CLng,如下所示:

Public Function LEFT_NUM(cv As String, ch As Long)
    cv = CStr(cv)
    output = Left(cv, ch)

    check = IsNumeric(output)

    If check = True Then
        LEFT_NUM = CLng(output) 'Changed on this line
    Else
        LEFT_NUM = output
    End If
End Function


Public Function RIGHT_NUM(cv As String, ch As Long)
    cv = CStr(cv)
    output = Right(cv, ch)

    check = IsNumeric(output)

    If check = True Then
        RIGHT_NUM = CLng(output) 'Changed on this line
    Else
        RIGHT_NUM = output
    End If
End Function