【问题标题】:Adding "A1,A2,A3.." to "B1,B2,B3.." Then Row "A" resets value to Zero将“A1,A2,A3..”添加到“B1,B2,B3..”然后行“A”将值重置为零
【发布时间】:2014-11-26 16:10:41
【问题描述】:

我目前正在尝试将脚本添加到 excel 中。原谅我的术语,我对编程不是那么热情!

我在 excel 2003 上完成了所有会计工作,我希望能够分别将单元格 f6f27 的值添加到单元格 e6e27 中。问题是,我希望每次都重置“f”列的值。

到目前为止,我已经找到了这段代码,如果我将它复制并粘贴到 VBA 中,它就可以工作。但它只允许我在一行上使用它:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    If Target.Address = Range("f7").Address Then
        Range("e7") = Range("e7") + Range("f7")
        Range("f7").ClearContents
    End If
    Application.EnableEvents = True
End Sub

有人能解释一下我如何编辑它以通过我想要的所有单元格来做同样的事情吗?我尝试添加 Range("f7",[f8],[f9] 等。但我真的超出了我的知识范围。

【问题讨论】:

  • edit 将您的问题标题改为描述您遇到的问题的内容。您已经在标签中包含了关于 Excel 和 VBA 的内容,很明显您需要帮助,否则您不会在这里询问,这意味着标题中的有意义的内容与现在一样为零。您的标题应表明该问题的一些内容,并且应该对未来的读者在搜索结果中找到它有用。

标签: excel vba excel-2003


【解决方案1】:

首先,您需要定义应该被“捕获”的范围;也就是说,定义要跟踪更改的范围。我找到了一个例子here。然后,只需将值添加到另一个单元格:

Private Sub Worksheet_Change(ByVal Target as Range)
    Dim r as Range ' The range you'll track for changes
    Set r = Range("F2:F27")

    ' If the changed cell is not in the tracked range, then exit the procedure
    ' (in other words, if the intersection between target and r is empty)
    If Intersect(Target, r) Is Nothing Then
        Exit Sub
    Else
        ' Now, if the changed cell is in the range, then update the required value:
        Cells(Target.Row, 5).Value = Cells(Target.Row, 5).Value + Target.Value
        ' ----------------^
        ' Column 5 = 
        '       column "E"

        ' Clear the changed cell
        Target.ClearContents
    End if
End Sub

希望对你有帮助

【讨论】:

  • 嗨。非常感谢你的回复。对不起,我真的不擅长这个。我解释说我应该在 VBA 中输入这个?? Private Sub Worksheet_Change(ByVal Target As Range) Dim r As Range Set r = Range("F2:F27") If Intersect(Target, r) is nothing then Exit Sub Else Cells(Target.Row, 5).Value = Cells( Target.Row, 5).Value + Target.Value Target.ClearContents End If End Sub
  • 非常感谢。只需要关闭宏安全!
  • @RhysDavies 乐于助人。顺便说一句,如果您觉得这很有用,请投票和/或接受它;)
【解决方案2】:

试试这个

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    If Intersect(Target, Range("B1:B5,F6:F27")) Then 'U can define any other range   
        Target.Offset(0, -1) = Target.Offset(0, -1).Value + Target.Value ' Target.Offset(0,-1) refer to cell one column before the changed cell column.
        'OR: Cells(Target.row, 5) = Cells(Target.row, 5).Value + Target.Value '  Where the 5 refer to column E
        Target.ClearContents
    End If

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2021-06-02
    • 2023-01-09
    • 2020-09-16
    相关资源
    最近更新 更多