Home » excel » excel – error 91 object variable or with block variable not set on range

excel – error 91 object variable or with block variable not set on range

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m new to VBA as was trying to write a macro that finds duplicates in different columns from a worksheet. I found the answer here helpful. However this solved it only for one column. So to add a few more columns I altered the code as follows

        Sub test()
    Dim iWarnColor As Integer
    Dim rng As Range
    Dim rngCell As Variant
    Dim iWarnColor1 As Integer
    Dim rnga As Range
    Dim rngCell1 As Variant


    Set rng = Range("A1:A17") ' area to check '
    iWarnColor = xlThemeColorAccent2

    For Each rngCell In rng.Cells
        vVal = rngCell.Text
        If (WorksheetFunction.CountIf(rng, vVal) = 1) Then
            rngCell.Interior.Pattern = xlNone
        Else
            rngCell.Interior.ColorIndex = iWarnColor
        End If
    Next rngCell

    Set rnga = Range("B1:B17") ' area to check '
    iWarnColor1 = xlThemeColorAccent3

    For Each rngCell1 In rnga.Cells
        vVal = rngCell1.Text
        If (WorksheetFunction.CountIf(rnga, vVal) = 1) Then
            rngCell1.Interior.Pattern = xlNone
        Else
            rngCell1.Interior.ColorIndex = iWarnColor1
        End If
    Next rngCell1
    End Sub

On running this code I get
“Run time error 91: object variable or with block variable not set “

It says the error is at

For Each rngCell1 In rnga.Cells

What am I doing wrong here??

How to&Answers:

I can run your code locally in Excel 2010 without any errors, so not sure exactly what the problem is.

Try to change the type of rngCell1 from Variant to Range and see if it makes any difference.

As a side note, vVal has not been Dimed. It will only complain if you add Option Explicit at the top of your module, so it shouldn’t matter here.