Excel vba中的“没有单元格发现错误”

我正在使用以下代码unMerge和复制单元格。 这是我正在使用的代码。

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 

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

如果没有find空白单元格,SpecialCells方法将会出错。 为了避免这种情况,您可以使用简单的error handling来跳过该错误

 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文档: https : MergeCells

关于SpecialCellsTypeBlanks,显然有一个已知的限制,不容易绕过它,因此应该使用On Error Resume Next ,虽然我真的不是这个错误捕获的粉丝 – https://www.rondebruin .NL / WIN / S4 / win003.htm

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