VBA类型不匹配错误与范围.值和范围.行



我有以下VBA代码,它似乎部分工作?有时有效,有时无效。我得到一个类型不匹配的错误在"如果Len(c.Value)>30和c.Row <>1";然后行。如有任何帮助,我将不胜感激。

Sub GSSLength()
Dim c As Range
Dim ws As Worksheet
Dim j As Long
j = 0
For Each ws In ActiveWorkbook.Worksheets    
If ws.Name Like "BOM" Then        
For Each c In ws.Range("A2:R10000")
If Len(c.Value) > 30 And c.Row <> 1 Then        
ws.Cells(c.Row, c.Column).Interior.ColorIndex = 3            
j = j + 1                
End If        
Next c    
End If
Next ws
If j > 0 Then
MsgBox j & " errors found where the length of cell is longer than 30 characthers, please correct in columns that are red."
End If
End Sub

我假设这不是你的最终代码…?您指定的范围永远不会有Row = 1,并且您在Like语句中使用"BOM",这似乎是不必要的。也许你只是为了这个问题才写这个。

忽略这些奇怪的地方,您可能在该区域中得到一个包含错误的单元格。你可以像这样把它们设置为:

For Each ws In ActiveWorkbook.Worksheets
If ws.Name Like "BOM" Then
For Each c In ws.Range("A2:R10000")

If Not (IsError(c)) Then
If Len(c.Value) > 30 And c.Row <> 1 Then
ws.Cells(c.Row, c.Column).Interior.ColorIndex = 3
j = j + 1
End If
End If
Next c
End If
Next ws

感谢所有的提示,我刚刚注意到我在单元格中有一个错误,它是一个数字格式而不是字符串,LEN函数在那里抛出了一个错误。

最新更新