首页 > 解决方案 > ActiveCell 更改然后在另一个单元格更改中添加

问题描述

请帮助我使用下面的宏,当我更改 activecell 中的值时,它无法正常工作。

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
   
    
    Dim KeyCells As Range
    
        kolumna = ActiveCell.Column
        wiersz = ActiveCell.Row
        komorka = Cells(wiersz, kolumna).Address
        Set KeyCells = Range(komorka)
       
If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

        Target.Offset(0, 1) = Target * 12
       
End If
Application.EnableEvents = True
End Sub

但是当我使用下面的代码时它可以工作,但是当我更改单元格中的值时它可以工作:$D$3

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    
    
    Dim KeyCells As Range
    
        Set KeyCells = Range("$D$3")
       
If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        Target.Offset(0, 1) = Target * 12
       
End If
Application.EnableEvents = True

End Sub

所以我的代码的问题就在这里:

komorka = Cells(wiersz, kolumna).Address

非常感谢你的帮助

标签: excelvba

解决方案


返回后移动

Application.MoveAfterReturn

  • MoveAfterReturn如果设置为,它将不起作用True,因为当您更改值时,光标会移动到下一个单元格,ActiveCell因此它们永远不会相交(更正:如果您在列中A并使用Left箭头确认条目,它仍然可以工作或在A1使用Up箭头等)。
  • 如果您设置MoveAfterReturn为,它可以工作False,所以我编写了切换它的过程。添加 aButton或 aCommandButton并在必要时使用它来启用或禁用它。
  • 请注意,您必须使用 确认单元格条目Enter。箭头不会做。

表模块例如Sheet1

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.MoveAfterReturn Then
        If Not Application.Intersect(ActiveCell, Target) Is Nothing Then
            Dim cValue As Variant: cValue = Target.Value
            If IsNumeric(cValue) Then
                Target.Offset(0, 1).Value = CDbl(cValue) * 12
            End If
        End If
    End If
End Sub

标准模块 例如Module1

Option Explicit

Sub toggleMAR()
    With Application
        If .MoveAfterReturn Then
            .MoveAfterReturn = False
        Else
            .MoveAfterReturn = True
        End If
    End With
End Sub

推荐阅读