VBA如果单元格长度不足,高亮显示消息

我正在尝试编写一个macros来检查Excel电子表格中的特定列,查找长度小于9个字符但大于2的条目,如果find,则显示一条消息并突出显示find该值的单元格。 这可能会发生多次。 我写了下面的代码:

Sub Highlight() Dim c As Range Dim LR As Integer Dim intCell As Long LR = Worksheets("Basket").Cells(Rows.Count, 6).End(xlUp).Row For intCell = 1 To 8 For Each c In Range("G20:G" & LR).Cells If Len(c.Value) < 9 And Len(c.Value) > 2 Then MsgBox "One or more of the codes is invalid. Correct the highlighted values." c.Cells(intCell).Interior.Color = vbYellow End If Next Next End Sub 

我无法弄清楚我做错了什么。 任何帮助将不胜感激。

只是猜测你想要突出什么

 Sub Highlight() Dim c As Range Dim LR As Integer Dim numProbs as long Dim sht as Worksheet Set sht=Worksheets("Basket") numProbs=0 LR = sht.Cells(Rows.Count, "G").End(xlUp).Row For Each c In sht.Range("G20:G" & LR).Cells If Len(c.Value) < 9 And Len(c.Value) > 2 Then c.entirerow.cells(1).Resize(1,8).Interior.Color = vbYellow numProbs=numProbs+1 End If Next if numProbs>0 Then msgbox "There were issues with " & numProbs & " rows. See yellow cells" end if End Sub 

试试下面的代码:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("A1:a10")) Is Nothing Then If Len(Target) <= 9 And Len(Target) >= 2 Then MsgBox " Length of string is " & Len(Target) Target.Font.Bold = True End If End If End Sub 

我已经使用范围A1:A10进行试用。