How to clear the contents of merged cells

I'm trying to clear the contents of cells, but some of them are merged, so I get an error

1004: "We cannot do this to merge cells"

For l = 4 To 9
    If ws.Cells(j, l).Interior.ColorIndex = 19 Then
         ws.Range(j, l).ClearContents  'Error here
    End If
Next l 

Other Try using .Cells, but it returns an error

    For l = 4 To 9
        If ws.Cells(j, l).Interior.ColorIndex = 19 Then
             ws.Cells(j, l).ClearContents  'Error here
        End If
    Next l 
+9
source share
4 answers

You need Cellsnot Range:

ws.Cells(j, l).ClearContents

Oops - forgot about the combined bit:

        If Cells(j, l).MergeCells Then
            Cells(j, l).MergeArea.ClearContents
        Else
            Cells(j, l).ClearContents
        End If
+12
source

Another thing that you create a macro and use the key combination (ctrl + m) so that you can select the cells you want to combine and clear. Here is the code:

Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+m
'
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        If .MergeCells = True Then
            .MergeCells = False
        Else
            .MergeCells = True
        End If
    End With
End Sub
0
source

ws.Range(j, l).Select
Selection.ClearContents

.

0

ws.Range(j,l).Clearcontents
-3

Source: https://habr.com/ru/post/1611924/


All Articles