VBA寻找选择的角落

Nor*_*rsk 7 excel vba

给定一个矩形Selection,如何找到Cell每个角的s?具体来说,右上角和左下角.

例如,如果用户选择范围B2:G9,我想从Selection对象获得每个角落的地址.

选择角落

我曾经.Address得到左上角和右下角,虽然我可以开始拆分字符串并执行正则表达式替换它们我想知道是否有更清洁的方法.

Sha*_*ado 9

你的意思是像下面的代码.

注意:最好是从远离SelectSelection,你可以尝试使用With Range("B2:G9")替代(未在下面的代码尚未实施)

Option Explicit

Sub GetRangeSelectionCorners()

Dim TopLeft As String, TopRight As String, BottomLeft As String, BottomRight As String
Dim TopLeftRow As Long, TopLeftCol As Long, BottomRightRow As Long, BottomRightCol As Long

Range("B2:G9").Select
With Selection
    TopLeft = .Cells(1, 1).Address '<-- top left cell in Selection
    TopRight = .Cells(1, .Columns.Count).Address '<-- top right cell in Selection
    BottomLeft = .Cells(.Rows.Count, 0.1).Address '<-- bottom left cell in selection
    BottomRight = .Cells(.Rows.Count, .Columns.Count).Address '<-- last cell in selection (bottom right)

    ' get row and column number
    TopLeftRow = .Cells(1, 1).Row '<-- top left cell's row
    TopLeftCol = .Cells(1, 1).Column '<-- top left cell's column
    BottomRightRow = .Cells(.Rows.Count, .Columns.Count).Row '<-- bottom right cell's row
    BottomRightCol = .Cells(.Rows.Count, .Columns.Count).Column  '<-- bottom right cell's column
End With

MsgBox "Top Left cell address is :" & TopLeft & vbCr & _
        "Top Right cell address is :" & TopRight & vbCr & _
        "Bottom Left cell address is :" & BottomLeft & vbCr & _
        "Bottom Right cell address is :" & BottomRight

MsgBox "Top Left cell's row is : " & TopLeftRow & _
        ", and column is :" & TopLeftCol & vbCr & _
        "Bottom Right cell's row is : " & BottomRightRow & _
        ", Bottom Right cell's column is :" & BottomRightCol

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 为什么`BottomLeft = .Cells(.Rows.Count,0.1).Address`中的`0.1`?为什么不`BottomLeft = .Cells(.Rows.Count,1).Address`? (3认同)