我还是编码和VBA的新手,有一个问题。我有一个交货日志,我正在其中记录供应商名称,收到的零件和退回的零件。我试图根据输入到同一行中接下来的两个单元格中的内容,将一个特定值附加或删除到具有我输入的供应商名称的单元格中。这就是我到目前为止所拥有的。
Sub Worksheet_Change(ByVal Target As Range)
Dim d As Variant
If Not Intersect(Target, Range("D:D")) Is Nothing Then
For Each d In Intersect(Target, Range("D:D"))
If d.Offset(0, -1).Value = 0 Or d.Offset(0, -1).Value = "" And
Intersect(Target, Range("D:D")) <> 0 Then
d.Offset(0, -2).Value = d.Offset(0, -2).Value + " (Credit)"
End If
If d.Offset(0, -1).Value <> 0 Or d.Offset(0, -1).Value <> "" And
Intersect(Target, Range("D:D")) <> 0 Or Intersect(Target, Range("D:D")) = 0 Then
d.Offset(0, -2).Replace What:=" (Credit)", Replacement:=""
End If
Next d
End If
End Sub
如果从左到右输入,它在基本级别上起作用,但是,如果在D6中输入值的同时删除了单元格C6中的值,则不会更新单元格B6以包括添加的((贷方)”的值以反映更改。
我还试图将其移动到如果单元格B6的值为空但D6中有一个值的位置,则不会将添加的值输入到B6。
如果这令人困惑,请原谅我。这是一个区域的屏幕抓图。
答案 0 :(得分:0)
请尝试以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
'Check if the changed cell should start the code
If Target.Row >= 6 And Target.Column >= 3 And Target.Column <= 4 Then
'Set cells as objects for easier manipulation
Set Vendor = Cells(Target.Row, 2)
Set Received = Cells(Target.Row, 3)
Set Returned = Cells(Target.Row, 4)
'Check if returned amount is bigger than received
If Returned > Received Then
'If so, check if the credit string is already placed
If InStr(Vendor, " (Credit)") = 0 Then
'If not, add ir
Vendor.Value = Vendor & " (Credit)"
End If
'If smaller, remove the credit tag
Else
Vendor.Value = Replace(Vendor, " (Credit)", "")
End If
End If
End Sub