Excel 单元格只接受写入的特定值
我刚开始使用vba,我想知道我是否可以在这里得到一些指导。我试图将范围a1:a50设置为只接受这样写的数字:即111.111.111或231.432.212。当我读到%在VBA中被定义为一个数字时,我使用%.%.%.%.%.%来设置它 但是,使用此格式%.%.%.%.%无法完成此任务。如果可能的话,有人能指导我解决这个问题吗?我必须感谢你Excel 单元格只接受写入的特定值,excel,vba,Excel,Vba,我刚开始使用vba,我想知道我是否可以在这里得到一些指导。我试图将范围a1:a50设置为只接受这样写的数字:即111.111.111或231.432.212。当我读到%在VBA中被定义为一个数字时,我使用%.%.%.%.%.%来设置它 但是,使用此格式%.%.%.%.%无法完成此任务。如果可能的话,有人能指导我解决这个问题吗?我必须感谢你 Dim cell As Range Application.EnableEvents = False For Each cell I
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
您可以使用RegEx来测试单元格值。您可以运行以下宏来查看其工作原理 有关如何在Excel中设置正则表达式的信息,请参见
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