从活动单元格中select一个单元格范围

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

例如,在样本数据中,如果活动单元格是G6,则代码将select从A2到J7的整个范围。 同样,如果活动单元格是F12,代码将select从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 

这将做你想要的:

 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 

考虑你的模板,也许这可以帮助:

 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 

PS抱歉我的英语

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

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