从vba excel的四个方向扩展活动细胞的范围

时间:2016-09-07 08:49:49

标签: excel-vba vba excel

我设法选择了一个包含内容的范围:

Selection.SpecialCells(xlCellTypeConstants, 23).Select

现在我想在四个方向上扩展该范围,可能有一个偏移功能。例如,我希望范围选择C3:D6变为B2:E7。

如果可能的话C3:D6; F3:G6; I3:J6变成B2:K7莫名其妙

1 个答案:

答案 0 :(得分:0)

一切皆有可能

enter image description here

Sub TestResizeAndMergeAreas()
    Dim r As Range

    Worksheets.Add

    Range("C3:D6,F3:G6,I3:J6").Value = "Test Data"

    Range("A1:Z20").Select

    On Error Resume Next
    Set r = Selection.SpecialCells(xlCellTypeConstants, 23)
    On Error GoTo 0

    If Not r Is Nothing Then
        Debug.Print "Before:", r.Address

        ResizeAndMergeAreas r, -1, 1, -1, 1

        Debug.Print "After:", r.Address
    End If

    r.Select
End Sub

Sub ResizeAndMergeAreas(ByRef Target As Range, x1 As Long, x2 As Long, y1 As Long, y2 As Long)
    Dim rArea As Range

    For Each rArea In Target
        Set Target = Range(Target, rArea)
    Next

    Set Target = Target.Offset(x1, y1).Resize(Target.Rows.Count + x2 + (x1 * -1), Target.Columns.Count + y2 + (y1 * -1))

End Sub