我有基本代码,允许在保持累积值的同时将写入此单元格的值相加。所以如果我输入" 4"进入单元格,然后键入" 10"进入细胞,结果将是" 14" (不只是输入的第二个值" 10")。这就是我所拥有的,我必须说它有效。
Option Explicit
Dim oldvalue As Double
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Address = "$J$5" Then
On Error GoTo fixit
Application.EnableEvents = False
If Target.Value = 0 Then oldvalue = 0
Target.Value = 1 * Target.Value + oldvalue
oldvalue = Target.Value
fixit:
Application.EnableEvents = True
End If
End Sub
但是,我想将这种治疗方法应用于细胞J5以上。比方说,我也希望将相同的代码逻辑应用于单元格R5 到目前为止,我已尝试使用
OR
我也尝试过使用
If Not Intersect (Target, Range("J5:R5")) Is Nothing Then
但是这些方法中的每一种都将两个单元连接在一起(因此我输入的单元被加到两个单元中 - 每个单元格将相加的值加到另一个单元格中)。我无法解决这个问题以挽救我的生命,所以请到这个论坛,希望找到一个比我聪明的人。
答案 0 :(得分:0)
也许(假设现有逻辑是正确的......不确定为什么如果Target = 0且* 1添加了什么值,你将旧值设置为0?)
Option Explicit
Dim oldvalueJ As Double
Dim oldValueR As Double
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
On Error GoTo fixit
Application.EnableEvents = False
Select Case Target.Address
Case "$J$5"
If Target = 0 Then oldvalueJ = 0
Target = Target + oldvalueJ
oldvalueJ = Target
Case "$R$5"
If Target = 0 Then oldValueR = 0
Target = Target + oldValueR
oldValueR = Target
End Select
fixit:
Application.EnableEvents = True
End Sub
答案 1 :(得分:0)
使用逗号分隔范围,并添加Worksheet_SelectionChange()
事件以记录最后一个用户选择的单元格
Option Explicit
Dim oldvalue As String
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Intersect(Target, Range("J5,R5")) Is Nothing Then Exit Sub
If Target.Value = 0 Then Exit Sub
On Error GoTo fixit
Application.EnableEvents = False
Target.Value = Target.Value + oldvalue
fixit:
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge = 1 Then oldvalue = Target.Value
End Sub
答案 2 :(得分:0)
允许您添加无限制的单元格,这有点动态;它还验证用户输入
标准模块
Option Explicit 'Sheet1 Module
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.CountLarge = 1 Then
If Not Intersect(Target, Me.Range(WS1_MEM_RNG)) Is Nothing Then GetPrevious Target
End If
End Sub
Private Sub GetPrevious(ByVal cel As Range)
Dim adr As String: adr = cel.Address
Application.EnableEvents = False
If Not IsError(cel.Value) And IsNumeric(cel.Value2) And Not IsNull(cel.Value) Then
If IsDate(cel.Value) Then
cel.NumberFormat = "General"
cel.Value2 = prevWs1Vals(adr)
Else
If cel.Value2 = 0 Then prevWs1Vals(adr) = 0
cel.Value2 = cel.Value2 + prevWs1Vals(adr)
prevWs1Vals(adr) = cel.Value2
End If
Else
cel.Value2 = prevWs1Vals(adr)
End If
Application.EnableEvents = True
End Sub
Sheet1 模块
Option Explicit 'ThisWorkbook Module
Private Sub Workbook_Open()
If prevWs1Vals Is Nothing Then Set prevWs1Vals = CreateObject("Scripting.Dictionary")
SetPreviousWS1Vals
End Sub
ThisWorkbook 模块
ENV['S3_BUCKET_NAME']
它也可以强制执行积极因素