vba 在excel中使用VBA选择单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19017929/
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
Selecting a cell with VBA in excel
提问by samuraiY
I am trying to select a cell in excel with vba. I want to be able to use to variables(i & e) to choose a cell. Where i = 3and e = 13I would like to be able to
我正在尝试使用 vba 在 excel 中选择一个单元格。我希望能够使用变量(i & e)来选择一个单元格。其中i = 3和e = 13我希望能够
ActiveCell(e, i).Activate
and it select cell C13.
并选择单元格C13。
ActiveCell(e, i).Activate
does work but only when original active cell is A1. Any help would be greatly appreciated!
确实有效,但仅当原始活动单元格为 A1 时。任何帮助将不胜感激!
回答by
I put comments in the code so it should be really easy to understand.
我在代码中添加了注释,所以它应该很容易理解。
Run the below code first
首先运行下面的代码
Sub Main()
Dim i As Long ' row variable
Dim e As Long ' column variable
i = 3 ' row 3
e = 13 ' column 13 ("M")
' this will put: Cells(3,13) in Range "M3"
Cells(i, e) = "Cells(" & i & ", " & e & ")"
' if you want to offset the current active cell then
' use Offset(x, y)
' use negative x to offset up
Cells(i, e).Offset(-1, 0) = "1 up"
' use positive x to offset down
Cells(i, e).Offset(1, 0) = "1 down"
' use negative y to offset left
Cells(i, e).Offset(0, -1) = "1 left"
' use positive y to offset right
Cells(i, e).Offset(0, 1) = "1 right"
' same principles apply when using range object
Dim r As Range
Set r = Cells(i, e)
r.Offset(-2, 0) = "2 up"
r.Offset(2, 0) = "2 down"
r.Offset(0, -2) = "2 left"
r.Offset(0, 2) = "2 right"
Columns.AutoFit
End Sub
then look at your sheet and analyse what command does what :)
然后看看你的工作表并分析什么命令做了什么:)