在excel中选择具有VBA的单元格

时间:2013-09-26 01:37:43

标签: excel vba excel-vba

我正在尝试使用vba选择excel中的单元格。我希望能够使用变量(i& e)来选择一个单元格。 i = 3 e = 13 我希望能够

ActiveCell(e, i).Activate

并选择单元格C13。

ActiveCell(e, i).Activate

确实有效,但仅当原始活动单元格为A1时才有效。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

我在代码中添加了注释,因此它应该很容易理解。

首先运行以下代码

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

然后查看您的工作表并分析命令执行的操作:)

enter image description here