代码之家  ›  专栏  ›  技术社区  ›  Forward Ed

检查单元格条目是否会生成错误的最佳实践

  •  1
  • Forward Ed  · 技术社区  · 1 年前

    情况:

    我使用单元格“D2”的内容命名工作表。我刚刚编辑了下面的代码,以捕获各种不同的问题条目,发布消息,并提供一个有效且明显需要替换的值。

    代码:

    Private Sub Worksheet_Change(ByVal Target As Range)
        
        Dim BadData As Boolean
        
        If Intersect(Target, ThisWorkbook.Sheets(2).Range("D2")) Is Nothing Then
            Exit Sub
        End If
        
       BadData = False
            
        If Len(Target.Value) > 31 Or IsEmpty(Target.Value) Then
            BadData = True
        ElseIf InStr(Target.Value, "[") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, "]") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, "*") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, "?") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, "\") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, "/") <> 0 Then
            BadData = True
        ElseIf InStr(Target.Value, ":") <> 0 Then
            BadData = True
        End If
        
        If BadData Then
            MsgBox "You have entered an unacceptable ID value." & vbCrLf & _
                    vbCrLf & _
                    "The Site No entry must:" & vbCrLf & _
                    vbCrLf & _
                    "1)  Be a value less than 31 characters long" & vbCrLf & _
                    "2)  Not contain the following characters:  /, \, :, ?, *, [, ]" & vbCrLf & _
                    "3)  Not be a blank value" & vbCrLf & _
                    "4)  Be compatible with excel sheet name restrictions"
                    
            Target.Value = "Enter Site ID"
        End If
        
        ThisWorkbook.Sheets(2).Name = Target.Value
    
    End Sub
    

    虽然上面的代码似乎有效,但我相信还有其他多种方法可以实现相同的最终结果。导致相同值的多个IF语句让我有点困扰。

    我最初想将所有单独的InStr检查放入一个带有Len和IS Empty检查的长OR语句中,但选择不这样做,因为我认为其他人来尝试并找出代码会很痛苦。我意识到ELSEIF可能有一些好处,如果结果为TRUE,则可以防止进行后续检查。

    提问

    我想知道是否有更好的方法来做到这一点?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Siddharth Rout    1 年前

    你可以把它放在一个函数中,然后使用它吗?通过这种方式,您可以维护(添加、删除条件)该函数。

    '~~> UNTESTED
    Private Function IsBadData(CellValue As Variant) As Boolean
        Dim BadString As String
        Dim BadData As Boolean
        Dim MyAr
        Dim i As Long
        
        BadString = "[,],*,?,\,/,:"
        
        If Len(Trim(CellValue)) = 0 or Len(Trim(CellValue)) > 31 Then
            BadData = True
        Else
            MyAr = Split(BadString, ",")
        
            For i = LBound(MyAr) To UBound(MyAr)
                If InStr(1, CellValue, MyAr(i)) Then
                    BadData = True
                    Exit For
                End If
            Next i
        End If
        
        IsBadData = BadData
    End Function
    

    使用方法 :

    If IsBadData(Target.Value) Then
        MsgBox "Blah Blah"
    End If