VBA Excel 宏:偏移单元格选择、宏定义的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6668827/
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-08 11:37:52  来源:igfitidea点击:

VBA Excel Macro: Offsetting Cell Selection, Selection as Defined by Macro

vbaexcel-vbaselectionoffsetexcel

提问by H3lue

I am writing a line of code as part of a more complex program that is not working correctly. I am new to VBA so please bear with me...

我正在编写一行代码,作为无法正常工作的更复杂程序的一部分。我是 VBA 新手,所以请耐心等待...

Essentially, I am prompting the user to select a cell which is then assigned to the variable 'celNm'.

本质上,我是在提示用户选择一个单元格,然后将该单元格分配给变量“celNm”。

I then perform the following actions:

然后我执行以下操作:

celNm.EntireRow.Copy
celNm.EntireRow.Insert

Next, for reasons specific to the program (and I am assuming the celNmwill be located at the same cell after the command [Not the same location]), I want to move the cell selection upwards, so it is now located at the row just recently copied above. I am using the following line to do this:

接下来,由于特定于程序的原因(我假设在celNm命令 [Not the same location] 之后将位于同一个单元格),我想向上移动单元格选择,所以它现在位于行最近复制上面。我正在使用以下行来执行此操作:

celNm.Offset(-1, 0).Select

This, however, does not work.

然而,这行不通。

The next step in the program would be to create a list in this location. However the program still creates a list at the previous location (in the cell selected). Why is this?

程序的下一步是在此位置创建一个列表。但是,程序仍会在上一个位置(在选定的单元格中)创建一个列表。为什么是这样?

回答by Excellll

celNm.Offset(-1,0).Selectonly selects the cell above celNm. It does not change the value of celNm. To change the value of celNm, you need the following:

celNm.Offset(-1,0).Select只选择 celNm 以上的单元格。它不会改变 celNm 的值。要更改 celNm 的值,您需要以下内容:

Set celNm = celNm.Offset(-1,0)

I'm assuming celNm is declared as a Range.

我假设 celNm 被声明为一个范围。

回答by Nick Heidke

I believe you'll need to work with ActiveCell. Here's an example (You'll want to change "A1" to your celNm variable):

我相信你需要与ActiveCell. 这是一个示例(您需要将“A1”更改为您的 celNm 变量):

Range("A1").Select
ActiveCell.Offset(-1, 0).Activate

Source

来源