简体   繁体   中英

AutoFill macro, error occured when there is merged cell in the column

I have the following code: it works well enough, but when the column gets merged cell it turns out to be in error. If there is any way to avoid count for the merged cell or be more specific - to count only data that contain only 7 characters in column B:

Sub Second()
Range("B15:I15").Select
Selection.AutoFill Destination:=Range("B15:I" & Range("B" & Rows.Count).End(xlUp).Row)
End Sub'

If the merged cell is always at the last row then it is easy. All you need to do is use the .MergeArea.Count to check if the last cell is merged.

在此处输入图片说明

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim Lrow As Long

    Set ws = ThisWorkbook.Sheets("Sheet2")

    With ws
        Lrow = .Range("B" & .Rows.Count).End(xlUp).Row

        If .Range("B" & Lrow).MergeArea.Count > 1 Then
            Lrow = Lrow - 1
        End If

        .Range("C15:I15").AutoFill Destination:=.Range("C15:I" & Lrow)
    End With
End Sub

在此处输入图片说明

And if you want to ignore the blank cell above the merged cell then, you can use this

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim Lrow As Long

    Set ws = ThisWorkbook.Sheets("Sheet2")

    With ws
        Lrow = .Range("B" & .Rows.Count).End(xlUp).Row

        If .Range("B" & Lrow).MergeArea.Count > 1 Then
            If Len(Trim(.Range("B" & Lrow - 1))) = 0 Then
                Lrow = .Range("B" & Lrow).End(xlUp).Row
            Else
                Lrow = Lrow - 1
            End If
        End If

        .Range("C15:I15").AutoFill Destination:=.Range("C15:I" & Lrow)
    End With
End Sub

在此处输入图片说明

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