简体   繁体   中英

“No Cells Found Error” in Excel vba

I am using following code to unMerge and copy the cells. This is the code i am using.

Sub unMerge()
    Dim lastRow As Long
    Dim lastCol As Long
    lastRow = Range("B2").End(xlDown).Row
    lastCol = Range("A2").End(xlToRight).Column

    For iCol = 1 To lastCol

        Columns(iCol).unMerge
        Columns(iCol).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=r[-1]c"

    Next iCol
End Sub

The code works smoothly when there are merged cells in the column however when a column is encountered without merged cells it give the Captioned Error. What could be the fault in the code.

If no blank cells are found, the SpecialCells method will error out. To avoid this, you may use simple error handling to skip that error

On Error Resume Next
Columns(iCol).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=r[-1]c"

If everything else runs smoothly, this is a good way to fix it:

Sub unMerge()
    Dim lastRow As Long
    Dim lastCol As Long
    Dim iCol As Long

    lastRow = Range("B2").End(xlDown).Row
    lastCol = Range("A2").End(xlToRight).Column

    For iCol = 1 To lastCol
        If Columns(iCol).MergeCells Then Columns(iCol).unMerge
        If RangeContainsCellTypeBlanks(Columns(iCol)) Then
            Columns(iCol).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=r[-1]c"
        End If
    Next iCol

End Sub

Public Function RangeContainsCellTypeBlanks(rng As Range) As Boolean

    On Error GoTo RangeContainsCellTypeBlanks_Error    
    If rng.Cells.SpecialCells(xlCellTypeBlanks).Count > 0 Then RangeContainsCellTypeBlanks = True

    On Error GoTo 0
    Exit Function    

RangeContainsCellTypeBlanks_Error:    
    RangeContainsCellTypeBlanks = False    
End Function

It checks for merged cells and if they are found it performs the unMerge and writes the FormulaR1C1. Here is the Microsoft documentation for the MergeCells property: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-mergecells-property-excel

Concerning the SpecialCellsTypeBlanks, there is obviously a known limitation which does not allow to go easily around it, and thus one should use the On Error Resume Next , although I am really not a fan of this error catching - https://www.rondebruin.nl/win/s4/win003.htm

Thus, at least I am using it in a boolean function, making sure it does not pollute the rest of the code.

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