vba 使用 Excel 宏选择范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6114526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 13:17:34  来源:igfitidea点击:

Range Selection Using Excel Macro

excelexcel-vbarangeselectionvba

提问by user768199

  A      B        C

123455  XXX     99999
123456  XX      100000
123457  XXX     100001
174564  XXXX    100002
184567          100003
194570          100004
204573          100005
214576          100006
224579          100007
                100008

I would like to write a macro for selecting a range using <ctrl> + <down arrow>

我想编写一个宏来使用 <ctrl> + <down arrow>

The process should be like this

流程应该是这样的

  1. Select cell A1
  2. Select a Range with <shift> + <ctrl> + <page down>
  3. Aelect cell A1 without cancelling the range selection (using <ctrl>)
  4. ActiveCell.Offset(0, 2).Select
  5. Then range select from C1 to C9 with <shift> + <ctrl> + <page down>then <shift> + <up arrow>
  1. 选择单元格 A1
  2. 选择一个范围 <shift> + <ctrl> + <page down>
  3. 在不取消范围选择的情况下选择单元格 A1(使用<ctrl>
  4. ActiveCell.Offset(0, 2).Select
  5. 然后从 C1 到 C9 的范围选择<shift> + <ctrl> + <page down>然后<shift> + <up arrow>

Following those steps in my example data, 224579 and 100007 are selected at same row, 100008 is not selected.

按照我的示例数据中的这些步骤,在同一行中选择了 224579 和 100007,未选择 100008。

I want to select the range between A1 to A9 also C1 to C9, but I want the macro to do this without defining a range like A1 and A9, because the range will probably change like A1 will change to A5 after some alterations. So, I want the macro to adapt and grab the numbers accordingly.

我想选择 A1 到 A9 和 C1 到 C9 之间的范围,但我希望宏在不定义 A1 和 A9 之类的范围的情况下执行此操作,因为该范围可能会像 A1 那样在一些更改后更改为 A5。所以,我希望宏能够适应并相应地获取数字。

回答by eggplant_parm

This should work if A1 is the active cell.

如果 A1 是活动单元格,这应该可以工作。

Union(Range(ActiveCell, ActiveCell.End(xlDown)), Range(ActiveCell.Offset(0, 2), ActiveCell.End(xlDown).Offset(0, 2))).Select

回答by GSerg

Not sure, but do you want this?

不确定,但你想要这个吗?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Static self_protect As Boolean

  If self_protect Then Exit Sub

  self_protect = True
  Set Target = Target.Areas(1)
  Application.Union(Target, Target.Offset(0, 2)).Select
  self_protect = False
End Sub

Paste the code into a worksheet code module and select a range on the sheet.

将代码粘贴到工作表代码模块中,然后在工作表上选择一个范围。