下面的代码可以正常工作直到一点。因此,如果代码中提到的范围内的单元格包含一个数字,即"12"
,则代码可以工作,并且单元格变为空。但是,如果单元格包含数字和文本,即"12amasa"
或"asa12"
,则代码不再有效。
我认为这部分:If IsNumeric(cell.Value) And cell.Value <> vbNullString Then
将完成这项工作,但事实并非如此。我想要的只是如果单元格包含一个数字,那么它应该是空的。只允许来自a-z的字母。我可以修复我的代码吗?
由于
Dim cell As Range
Application.EnableEvents = False
For Each cell In Target
If Not Application.Intersect(cell, Range("a5:a10000")) Is Nothing Then
If IsNumeric(cell.Value) And cell.Value <> vbNullString Then
cell.Value = vbNullString
cell.Interior.Color = RGB(255, 0, 0)
Else
cell.Interior.Color = RGB(1000, 1000, 1000)
End If
End If
Next cell
Application.EnableEvents = True
答案 0 :(得分:1)
您需要遍历检查数值的字符,或循环查看可能的数值以查看它是否在字符串中。
使用第二种方法可能是:
Dim cell As Range
Dim i As Long
Dim Matched As Boolean
Application.EnableEvents = False
For Each cell In Target
If Not Application.Intersect(cell, Range("a5:a10000")) Is Nothing Then
Matched = False
For i = 0 To 9
If Instr(CStr(cell.Value), CStr(i)) > 0 Then
Matched = True
Exit For
End If
Next
If Matched Then
cell.Value = vbNullString
cell.Interior.Color = RGB(255, 0, 0)
Else
cell.Interior.Color = RGB(1000, 1000, 1000)
End If
End If
Next cell
Application.EnableEvents = True
您也可以使用RegEx执行此操作,但我从未使用它们,因此其他人必须证明这一点。
当然,我忽略了最明显的答案...... Like
运算符:
Dim cell As Range
Application.EnableEvents = False
For Each cell In Target
If Not Application.Intersect(cell, Range("a5:a10000")) Is Nothing Then
If CStr(cell.Value) Like "*[0-9]*" Then
cell.Value = vbNullString
cell.Interior.Color = RGB(255, 0, 0)
Else
cell.Interior.Color = RGB(1000, 1000, 1000)
End If
End If
Next cell
答案 1 :(得分:0)
这也可以使用正则表达式来实现,在更复杂的情况下非常有用:
Dim RE As Object, RE2 As Object
Set RE = CreateObject("VBScript.RegExp"): Set RE2 = CreateObject("VBScript.RegExp")
RE.Pattern = "[0-9][a-zA-Z]": RE2.Pattern = "[a-zA-Z][0-9]"
For Each cell In target
If Not Application.Intersect(cell, Range("a5:a10000")) Is Nothing Then
If RE.test(cell.Value) Or RE2.test(cell.Value) Then
cell.Value = vbNullString
cell.Interior.Color = RGB(255, 0, 0)
Else
cell.Interior.Color = RGB(1000, 1000, 1000)
End If
End If
Next cell