简体   繁体   中英

Highlight any cell without specific characters (lower case a-z) inside

I have some garbled characters (or, not garbled, but non-English characters such as A's with Scandinavian accents, etc), and I need to ferret them out of around 80,000 entries.

Can I write a formula to pick up and flag any cell that contains anything other than

abcdefghijklmnopqrstuvwxyz?

The following worked for me:

Option Explicit
Sub NonAscii()
    Dim UsedCells   As Range, _
        TestCell    As Range, _
        Position    As Long, _
        StrLen      As Long, _
        CharCode    As Long

    Set UsedCells = ActiveSheet.Range("A1:A4271").CurrentRegion
    For Each TestCell In UsedCells
        StrLen = Len(TestCell.Value)
        For Position = 1 To StrLen
            CharCode = Asc(Mid(TestCell, Position, 1))
            If CharCode < 97 Or CharCode > 122 Then
                TestCell.Interior.ColorIndex = 36
                Exit For
            End If
        Next Position
    Next TestCell
End Sub

My tiny solution to this, would be using RegExp:

Public Function demo(ByRef rngTarget As Range) As Boolean
  Dim objRE As Object
  Set objRE = CreateObject("vbscript.regexp")
  With objRE
    .Pattern = "[^a-z]"
    .Global = True

    'test will resolve true on any character other than a-z
    demo = .Test(rngTarget.Value)
  End With
  Set objRE = nothing
End Function

Put this code into a module, then use it as a formula for a conditional format on the cells you want to test.

Formula would look as simple as this: =demo(A1)

If you need more information to this: MSDN

You can of course use VBA to test all used cells:

'This code needs to be placed as a worksheet macro, 
'or a worksheet needs to be specified for UsedRange
Public Sub TestAll()
  Dim rngCell as Range

  For Each rngCell In UsedRange.Cells
    if demo(rngCell) then
       rngCell.interior.color = RGB(125,125,125)
    end if
  Next rngCell
End Sub

You can use Conditional Formatting for this which will highlight cells in-situ rather than needing to test each cell with a seprate formula or VBA

This formula validates that each character in A1 is lowercase az

SUMPRODUCT(--((CODE(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1))>=97)),--(CODE(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1))<=122))<>LEN(A1)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM