简体   繁体   English

Excel vba中的“No Cells Found Error”

[英]“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. 如果未找到空白单元格,则SpecialCells方法将出错。 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. 它检查合并的单元格,如果找到它们,则执行unMerge并写入FormulaR1C1。 Here is the Microsoft documentation for the MergeCells property: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-mergecells-property-excel 以下是MergeCells属性的Microsoft文档: httpsMergeCells

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 关于SpecialCellsTypeBlanks,显然有一个已知的限制,不允许轻松绕过它,因此应该使用On Error Resume Next ,虽然我真的不喜欢这个错误捕获 - 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. 因此,至少我在布尔函数中使用它,确保它不会污染其余的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM