单元格仅接受写入的特定值

时间:2018-01-03 10:04:32

标签: excel vba

我刚刚开始使用vba,我想知道我是否可以在这里获得一些指导。我试图设置范围a1:a50只接受这样写的数字:即111.111.111或231.432.212。我通过使用%%%。%%%。%%%来设置它,因为我读到%被定义为VBA中的数字。

但是,使用此格式%%%。%%%。%%%不起作用。如果有可能,任何人都可以指导我解决这个问题吗?必须赞赏。

Dim cell As Range
     Application.EnableEvents = False
        For Each cell In Target
         If Not Application.Intersect(cell, Range("a1:a50")) Is Nothing Then
           If Not cell.Value = %%%.%%%.%%% Then
               cell.Interior.Color = RGB(0, 0, 255)

       Else

           cell.Interior.Color = RGB(1000, 1000, 1000)
           End If
        End If
   Next cell
    Application.EnableEvents = True

1 个答案:

答案 0 :(得分:2)

您可以使用RegEx测试单元格值。您可以运行以下宏来查看它是如何工作的。

有关如何在Excel中设置RegEx的信息,请参阅here

Sub Test_Reg()
Dim regEx As New RegExp
Dim strPattern As String: strPattern = "[0-9]{3}.[0-9]{3}.[0-9]{3}"
'Note: if you want to exact match 9 numbers with two dots, 
'      then use strPattern = "^[0-9]{3}.[0-9]{3}.[0-9]{3}$"
strInput1 = "111.111.111"
strInput2 = "1234.1234.1234"
strInput3 = "12.12.12"
strInput4 = "12a.12a.12a"


    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With
    MsgBox (regEx.Test(strInput1))
    MsgBox (regEx.Test(strInput2))
    MsgBox (regEx.Test(strInput3))
    MsgBox (regEx.Test(strInput4))

End Sub

然后您的代码可以像这样修改:

Dim regEx As New RegExp
Dim strPattern As String: strPattern = "[0-9]{3}.[0-9]{3}.[0-9]{3}"
'Note: if you want to exact match 9 numbers with two dots, 
'      then use strPattern = "^[0-9]{3}.[0-9]{3}.[0-9]{3}$"
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With
Dim cell As Range
     Application.EnableEvents = False
     For Each cell In Target
         If Not Application.Intersect(cell, Range("a1:a50")) Is Nothing Then
           If (NOT regEx.Test(cell.Value)) Then
               cell.Interior.Color = RGB(0, 0, 255)

       Else

           cell.Interior.Color = RGB(1000, 1000, 1000)
           End If
        End If
   Next cell
   Application.EnableEvents = True