从“活动单元格”中选择一系列单元格

时间:2016-05-10 17:08:18

标签: excel vba excel-vba

我需要以下代码的帮助。我想要做的是,从活动单元格(可能是任何单元格)开始,选择右侧的所有单元格(=第一列)+左侧的所有单元格(=最后一列)+上面的所有单元格直到突出显示的行+下面的所有单元格,直到突出显示的行。请参阅附件Sample Data

例如,在样本数据中,如果活动单元格是G6,则代码将选择从A2到J7的整个范围。类似地,如果活动单元格是F12,则代码将选择从A11到J13的整个范围。

Sub sel()
Dim LastCol As Long
With ActiveSheet
    LastCol = .Range("A1").SpecialCells(xlCellTypeLastCell).Column
Dim FirstCol As Long
With ActiveSheet
LastVrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range(Cells(WorksheetFunction.Max(1, Selection.Row, LastVrow), _
  WorksheetFunction.Max(1, Selection.Column, LastCol)), _
  Cells(WorksheetFunction.Min(Selection.Worksheet.Rows.Count, _
  Selection.Row), _
  WorksheetFunction.Min(Selection.Worksheet.Columns.Count, _
  Selection.Column, FirstCol))).Select
 End With
End With
 End With
End Sub

3 个答案:

答案 0 :(得分:2)

这将做你想要的:

Sub foo2()
Dim rng As Range
Dim st As Long
Dim fin As Long
With Selection
    If Cells(.Row - 1, 1) <> "" Then
        st = Cells(.Row, 1).End(xlUp).Row
        If st = 1 Then st = 2
    Else
        st = .Row
    End If
    If Cells(.Row + 1, 1) <> "" Then
        fin = Cells(.Row, 1).End(xlDown).Row
    Else
        fin = .Row
    End If
    Set rng = Range("A" & st & ":J" & fin)

End With
rng.Select
End Sub

答案 1 :(得分:1)

考虑你的模板,也许这可能有所帮助:

sub sel()
    dim selectRowS as integer
    dim selectRowE as integer    

    with Selection    

        selectRowS = .row
        selectRowE = .row

        If Cells(.row + 1, 1) <> ""
            selectRowE = .end(xlEnd).row
        End If 
        If Cells(.row - 1, 1) <> ""
            if .row - 1 = 1 then
                selectRowS = 2
            Else
                selectRowS = .end(xlUp).row
            End if
        End If 

        Range(Cells(selectRowS,1),Cells(selectRowE,10)).select

    End With
End Sub

P.S。对不起我的英文

答案 2 :(得分:0)

也许你可以试试这个。无论activecell单元在哪里,首先将其移动到第一个位置,然后选择整个数据块。

Sub Sel()

    Selection.End(xlToLeft).Select 
    Selection.End(xlUp).Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select

End Sub
相关问题