繁体   English   中英

Excel vba中的“No Cells Found Error”

[英]“No Cells Found Error” in Excel vba

我使用以下代码来取消并复制单元格。 这是我正在使用的代码。

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

当列中有合并的单元格时,代码可以顺利运行,但是当遇到没有合并单元格的列时,它会给出标题错误。 什么可能是代码中的错误。

如果未找到空白单元格,则SpecialCells方法将出错。 为避免这种情况,您可以使用简单的错误处理来跳过该错误

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

如果其他一切顺利运行,这是解决它的好方法:

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

它检查合并的单元格,如果找到它们,则执行unMerge并写入FormulaR1C1。 以下是MergeCells属性的Microsoft文档: httpsMergeCells

关于SpecialCellsTypeBlanks,显然有一个已知的限制,不允许轻松绕过它,因此应该使用On Error Resume Next ,虽然我真的不喜欢这个错误捕获 - https://www.rondebruin .NL / WIN / S4 / win003.htm

因此,至少我在布尔函数中使用它,确保它不会污染其余的代码。

暂无
暂无

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

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