如何根据单元格更改访问同一行中的其他单元格?

时间:2019-07-29 11:13:54

标签: excel vba

我更改单元格中的值,我想在同一行但不同列上打印/获取该单元格。这是示例:

Col1 Col2

a   
b    10
c   

当我在第三行Col2中添加10时,我希望看到一个消息框,在第三行Col1中有值,即“ b”。

行索引不应限于示例中的3。

编辑:我将在Col2下的任何单元格上添加一些值,并且我想要一个宏将该值自动添加到左栏中。

2 个答案:

答案 0 :(得分:1)

在所需的工作表中使用Worksheet.Change event。它会触发任何单元格的每次更改。您可以使用Application.Intersect method来限制代码以在第2列中的更改触发。

最后,可以通过设置ColumnOffset参数,使用Range.Offset property从已更改的单元格移至另一列。负值会在当前单元格的正左侧向右移动。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim AffectedRange As Range
    Set AffectedRange = Intersect(Target, Me.Columns(2)) 'check if the change was in column 2

    If Not AffectedRange Is Nothing Then 'run the code only if column 2 was changed
        Dim Cell As Range
        For Each Cell In AffectedRange 'run this code for every cell in column 2 that  was changed
            If Cell.Value = 10 Then 'test if the cell was changed to 10
                MsgBox Cell.Offset(ColumnOffset:=-1).Value 'return the value of the cell one left (-1) of the cell that was changed
            End If
        Next Cell
    End If
End Sub

答案 1 :(得分:0)

Cells(yourRange.Row, anyColumnNumberYouWish)

Cells(Range("B3").Row, 1)
相关问题