我试图为我的细胞开发一个面具,根据要求它只需要文字或数字。
我也有一个干净的按钮来重置我各自的细胞。这是我的问题。我的掩码检查宏工作正常,但如果我使用我的干净按钮并且它们变空,同样的检查宏说明空白是不被接受的。
关注我的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
If Not Intersect(Target, Range("C5")) Is Nothing Then
If Not IsNumeric(Range("C5").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
Range("C5").Value = "" & Format(Range("C5").Value, "")
End If
If Not Intersect(Target, Range("C7")) Is Nothing Then
'apaga se nao for o numero
If Not IsNumeric(Range("C7").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
Range("C7").Value = "'" & Format(Range("C7").Value, "")
End If
If Not Intersect(Target, Range("I9")) Is Nothing Then
'apaga se nao for o numero
If Not IsNumeric(Range("I9").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
End If
If Not Intersect(Target, Range("I11")) Is Nothing Then
'apaga se nao for o numero
If Not IsNumeric(Range("I11").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
End If
If Not Intersect(Target, Range("I13")) Is Nothing Then
'apaga se nao for o numero
If Not IsNumeric(Range("I13").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
End If
If Not Intersect(Target, Range("E15")) Is Nothing Then
'apaga se nao for o numero
If Not IsNumeric(Range("E15").Value) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
End If
If Not Application.IsText(Worksheets("Formulário").Range("C9")) Then
MsgBox "Valor inválido."
Application.Undo
GoTo LetsContinue
End If
LetsContinue:
Application.EnableEvents = Truea
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Function IsAlpha(str As String) As Boolean
Dim c As String
Dim I As Integer
For I = 1 To Len(str)
c = Mid(str, I, 1)
Select Case Asc(c)
Case 32, 65 To 90, 97 To 122
IsAlpha = True
Case Else
IsAlpha = False
End Select
If Not IsAlpha Then Exit For
Next I
End Function
答案 0 :(得分:0)
尝试使用以下例程,使用VBA样式的正则表达式来测试您的规则:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Union(Range("C5"),Range("C7"), Range("I9")) Is Nothing Then Exit Sub
Application.EnableEvents = False
If Not Target.Value Like "[a-zA-Z0-9]+" Then
MsgBox "Valor inválido."
Application.Undo
End If
Application.EnableEvents = True
End Sub
然后在您的宏中“清理”单元格,请确保在开头使用Application.EnableEvents = False
并在结尾使用Application.EnableEvents = True
,这会阻止事件触发,这意味着上面的代码当您的宏更改单元格的值时,不会运行。