vba - 从事件单元格开始选择一系列单元格

标签 vba excel

我需要以下代码的帮助。我想做的是,从事件单元格(可以是任何单元格)开始,选择右侧的所有单元格(=第一列)+左侧的所有单元格(=最后一列)+上面的所有单元格,直到突出显示的行+下面的所有单元格,直到突出显示的行。见附件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

最佳答案

这将做你想要的:

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

关于vba - 从事件单元格开始选择一系列单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144852/

相关文章:

excel - 使用 instr 从出现在另一个表行中的源表行中查找 3 个匹配的单元格值

Java 流将 excel CSV 收集到基于列的总和过滤的列表中

vba - 将行更改的公式向下拖动除一个间隔之外的另一个间隔

excel - 使用 Excel VBA 显示 CommandBar 按钮的标题

arrays - 复制列时如何保持真正的空白单元格

VBA 为什么我必须将类变量变暗为变体,而不是其类型?

arrays - Excel VBA - 分配数组更改 LBound 和 UBound

c - Excel VBA 不能很好地与 C dll 一起用于小数 - 与整数一起工作

excel - 在所选单元格或行下方插入新行

Excel宏将数据从一个工作表复制并粘贴到另一个工作表