检查单元格是否包含数字

问题描述 投票:1回答:2

下面的代码工作正常,直到一点。因此,如果代码中提到的范围内的单元格包含一个数字,即"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
excel excel-vba vba
2个回答
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

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
© www.soinside.com 2019 - 2024. All rights reserved.