Excel VBA: How to Extend a Range Given a Current Selection

你离开我真会死。 提交于 2019-12-03 13:53:30
Range(Cells(WorksheetFunction.Max(1, Selection.Row - 1), _
      WorksheetFunction.Max(1, Selection.Column - 1)), _
      Cells(WorksheetFunction.Min(Selection.Worksheet.Rows.Count, _
      Selection.Row + 1), _
      WorksheetFunction.Min(Selection.Worksheet.Columns.Count, _
      Selection.Column + 1))).Select

upd: thanks Siddharth Rout for formating my msg

Siddharth Rout

You mean like this?

SYNTAX

ExpandRange [Range], [Number of Col on left], [Number of Rows on Top], [Number of Col on right], [Number of Rows down]

Sub Sample()
    Debug.Print ExpandRange(Range("B5"), 1, 1, 1, 1)            '<~~ $A$4:$C$6
    Debug.Print ExpandRange(Range("A1"), 1, 1, 1, 1)            '<~~ Error
    Debug.Print ExpandRange(Range("XFD4"), 1, 1, 1, 1)          '<~~ Error
    Debug.Print ExpandRange(Range("XFD1048576"), 1, 1, 1, 1)    '<~~ Error
    Debug.Print ExpandRange(Range("E5"), 1, 1, 1, 1)            '<~~ $D$4:$F$6
End Sub

Function ExpandRange(rng As Range, lft As Long, tp As Long, _
rt As Long, dwn As Long) As String
    If rng.Column - lft < 1 Or _
       rng.Row - tp < 1 Or _
       rng.Column + rt > ActiveSheet.Columns.Count Or _
       rng.Row + dwn > ActiveSheet.Rows.Count Then
        ExpandRange = "Error"
        Exit Function
    End If

    ExpandRange = Range(rng.Offset(-1 * tp, -1 * lft).Address & ":" & _
                        rng.Offset(dwn, rt).Address).Address
End Function
g3t_

Here is the simple code that I use to resize an existing selection.

Selection.Resize(Selection.Rows.Count + 5, Selection.Columns.Count + 50).Select

This will add 5 to the row count and 50 to the column count. Adapt to suit your needs.

You can use Application.WorksheetFunction.Offset() which is richer than VBA's Offset and does everything required by the question.
I think it does what Siddharth Rout ExpandRange does, without the need of a UDF.

Instead of returning an absolute address, I modifying the syntax above to return a range. Credit goes to Siddharth Rout = )

Function ExpandRG(rng As Variant, lft As Long, tp As Long, rt As Long, dwn As Long) _
 As Range
 Set ws = rng.Parent
If rng.Column - lft < 1 Or _
   rng.Row - tp < 1 Or _
   rng.Column + rt > ActiveSheet.Columns.Count Or _
   rng.Row + dwn > ActiveSheet.Rows.Count Then
        MsgBox "Out of range"
        Exit Function
End If

 Set rng = ws.Range(rng.Offset(-1 * tp, -1 * lft).Address & ":" & _
                    rng.Offset(dwn, rt).Address)                        
End Function

Sub aa()
Dim ori_add, O_add, New_add As Range
Set ori_add = Range("B2")
Set O_add = ori_add

Call ExpandRG(ori_add, 1, 1, 1, 1)
Set New_add = ori_add

MsgBox "Original address " & O_add.Address & ", new address is" & New_add.Address
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!