简体   繁体   English

Excel - 在字符串中查找第一个不为 0 的字符

[英]Excel - Finding first character that is not 0 in a string

My cell A1 will have a string in it such as 02020. I need a formula that will check this string and return the value of the first character that is not equal to 0. So in the above example it should return 2.我的单元格 A1 中将有一个字符串,例如 02020。我需要一个公式来检查此字符串并返回不等于 0 的第一个字符的值。因此在上面的示例中,它应该返回 2。

Thanks for any help.谢谢你的帮助。

The only important issue is that a leading zero may be the first character in a string of characters, or it may simply be the result of formatting a numeric value with leading zeros.唯一重要的问题是前导零可能是字符串中的第一个字符,或者它可能只是用前导零格式化数值的结果。 The solution should cover both cases.解决方案应涵盖这两种情况。

Consider this User Defined Function:考虑这个用户定义的函数:

Public Function DropTheZeros(r As Range) As Variant
    Dim s As String, i As Long

    s = r(1).Text
    For i = 1 To Len(s)
        DropTheZeros = Mid(s, i, 1)
        If DropTheZeros <> "0" Then Exit Function
    Next i
    DropTheZeros = ""
End Function

在此处输入图片说明

This should work even if the leading zeros are an artifice of formatting.即使前导零是格式化的技巧,这也应该有效。

Or even:甚至:

Public Function DropTheZeros2(r As Range) As Variant
    DropTheZeros2 = Left(Replace(r(1).Text, "0", ""), 1)
End Function

Or even without VBA:甚至没有 VBA:

=LEFT(SUBSTITUTE(TEXT(A1,"@"),"0",""),1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM