【问题标题】:Ensure Cell Value Follows a Specified Character & Number Combination确保单元格值遵循指定的字符和数字组合
【发布时间】:2018-08-03 11:36:03
【问题描述】:

我是 vba 新手,我有一个要求,我将输入限制在工作表的 A 列,用户只能输入以下格式的字符串

'BATCH00_00' 数字的范围是 0-99 我尝试了下面的代码,但它不起作用

Private Sub Worksheet_Change(ByVal Target As Range)
'PURPOSE: Checks a specific column and validates that value follow a specified pattern (numbers or letter combinations)
Dim cell As Range, rng As Range
Dim InvalidCount As Long, x As Long
x = 3 'Column to Validate
Set rng = ActiveSheet.UsedRange.Columns(x).Offset(1).Resize(ActiveSheet.UsedRange.Rows.Count - 1, 1)
For Each cell In rng.Cells
  If Not UCase(cell.Value) Like "BATCH##_##Then
    'Highlight Invalid Cell Yellow
      msg "invalid entry please enter In following format BATCH00_00"

    Next cell
End Sub

另外我在工作表上有另一个代码,它在 A 列中检查不应该有任何重复的条目

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, r As Range, msg As String, x As Range
Set rng = Intersect(Columns(1), Target)
If Not rng Is Nothing Then
Application.EnableEvents = False
For Each r In rng
If Not IsEmpty(r.Value) Then
If Application.CountIf(Columns(1), r.Value) > 1 Then
msg = msg & vbLf & r.Address(0, 0) & vbTab & r.Value
If x Is Nothing Then
                    r.activate
                    Set x = r
                Else
                    Set x = Union(x, r)
                End If
            End If
        End If
    Next
    If Len(msg) Then
        MsgBox "Duplicate values not allowed Invalid Entry" & msg
        x.ClearContents
        x.Select
   End If
    Set rng = Nothing
    Set x = Nothing
    Application.EnableEvents = True
End If
End Sub

如何使第一个代码正常工作并将两者结合以拥有一个 Private Sub Worksheet_Change

【问题讨论】:

    标签: vba macos excel


    【解决方案1】:

    试试这个(代码中的注释)

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim validationError Boolean
        validationError = False
        'if changed cell was not in A column, then exit sub
        If Target.Column <> 1 Then Exit Sub
        'check if format is valid BATCH00_00
        If Not Target.Value Like "BATCH[0-9][0-9]_[0-9][0-9]" Then
            MsgBox "Invalid format!"
            validationError = True
            Exit Sub
        End If
        'check for uniqueness in A column
        If Application.WorksheetFunction.CountIf(Range("A:A"), Target.Value) > 1 Then
            MsgBox "Values must be unique in A column!"
            validationError = True
        End If
    
        If validationError Then
            Application.EnableEvents = False
            Target.Value = ""
            Application.EnableEvents = True
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      相关资源
      最近更新 更多