我在VBA上的功能确实给出了一些误报输出

时间:2016-09-19 09:46:57

标签: vba excel-vba excel-formula excel

最近,我写了一个代码,以检查在德国发行的社会保险号码 我有3个输出:姓氏,dob和给定的社会保险号码。在第3位和第8位之间,它包括日期月和出生后的最后两年。 但是,在某些情况下,它确实会返回假阴性。有人可以建议任何改进吗?我对VBA和编码很新,这就是为什么随意检查并提出任何改进建议 我将发布我的代码,一个例子,它给出了真正的正面和例子,它确实给出了假阴性。

__ Steinbach 01.12.1991 12011291S533

的假阴性结果

Akyol 31.10.1993 13311093A017__
Voormann 22.11.1995 53221195V018__
Köhler15.10.199714151097K056__
Xheladini 22.10.1991 65221091X509__

Visual Basic中的函数

Public Function firstDigitsSocIn(surname As String, dob As Date, socialSecurityNumber As String) As String
        'defining variables (add gender after surname when data is available)

        Dim dayOfMonth As Integer
        Dim monthSoc As Integer
        Dim yearSoc As Integer
        Dim firstCharSurname As String
        Dim customMadeNumber As String
        'Dim genderCode As Integer            enable when having genders in data set
        'Dim genderCheck As Boolean
        Dim resultFirst7Chars As Boolean
        Dim resultInclGenderCheck As Boolean
        Dim resultFinal As Boolean
        'setting up variables with correct values

        dayOfMonth = Day(dob)
        monthSoc = Month(dob)
        yearSoc = Right(Year(dob), 2)
        firstCharSurname = Left(surname, 1)
        'genderCode = Left(Right(socialSecurityNumber, 3), 2)


        'if gender = "M" am

        'custommadenumber is composed using the credentials of the user
        customMadeNumber = dayOfMonth & monthSoc & yearSoc & firstCharSurname

        resultFirst7Chars = StrComp(Mid(socialSecurityNumber, 3, 7), customMadeNumber, vbBinaryCompare)

        'If gender = "M" And genderCode < 50 Then
        'genderCheck = True
        'ElseIf gender = "F" And genderCode > 50 Then
        'genderCheck = True
        'Else
        'genderCheck = False
        'End If

        'resultInclGenderCheck = resultFirst7Chars And genderCheck

        'resultFinal = resultInclGenderCheck And True 'put Pruefziffer check here as well

        firstDigitsSocIn = resultFirst7Chars

End Function

1 个答案:

答案 0 :(得分:4)

我认为你有两个严重的问题。

  1. 您使用Integer而非字符串构建自定义数字。这意味着少于10的数字将失去领先的0。

  2. 当您实际只想检查字符串是否相等时,可以使用StrComp。这不会太糟糕,但是你将结果转换为Boolean(因为resultFirst7Chars是一个布尔值)。如果字符串相等,则StrComp返回0,否则返回-1或+1。但当你将0,-1和1视为布尔值时,你会得到FalseTrueTrue,这与你想要的完全相反!

  3. Prakash已经解决了第二个问题。另一个是使用

    resultFirst7Chars = (socialSecurityNumber = customMadeNumber)
    

    编辑:由于Prakash在这里删除了他的答案,他建议:

    resultFirst7Chars = (StrComp(Mid(socialSecurityNumber, 3, 7), customMadeNumber, vbBinaryCompare) = 0)
    

    即。检查StrComp是否返回0。

    对于第一个问题,您可以使用dayOfMonth = Format(Day(dob), "00")获取前导零(声明dayOfMonth,其他为字符串,否则您将再次丢失它们!)

    Dim dayOfMonth As String 
    '...
    Dim yearSoc As String 
    
    dayOfMonth = Format(Day(dob), "00")
    '...
    yearSoc = Right(CStr(Year(dob)))  'CStr wouldn't be necessary but this way it's more obvious what is happening.
    

    最后,你的函数应该返回一个布尔值而不是一个字符串。