0

I have the following VBA code and it seems to work partially? Sometimes it works, and sometimes it doesnt. I am getting a type mismatch error on the "If Len(c.Value) > 30 And c.Row <> 1" Then line. Any help would be great, thanks.

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
4
  • 2
    what is the value of c when it fails? Commented Jul 7, 2022 at 14:02
  • 2
    Most likely there is an error within the cell that fails, e.g. division by zero or sth else Commented Jul 7, 2022 at 14:03
  • 2
    c.Row <> 1 will always be True by the way, if you're looping over ws.Range("A2:R10000"). Commented Jul 7, 2022 at 14:03
  • 2
    c is already referencing the row and column as well so you could consolidate ws.Cells(c.Row, c.Column).Interior.ColorIndex = 3 to c.Interior.ColorIndex = 3 Commented Jul 7, 2022 at 14:16

2 Answers 2

2

I'm assuming this isn't your final code..? The range you've specified will never have Row = 1 and you're using "BOM" in a Like statement that seems unnecessary. Maybe you've put this in just for this question.

Ignoring those oddities, you've probably got a cell in that range that contains an error. You can trap these out like so:

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
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for all the tips, I just noticed that I had an error in my cells where it was a number format instead of a string, and the LEN function was throwing an error there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.