简体   繁体   English

具有不同目标的Excel 2工作表事件

[英]Excel 2 Worksheets Events with Different Targets

I have an excel worksheet that I want to assign to it more than one Worksheet Event. 我有一个Excel工作表,我想为其分配多个工作表事件。 To be more specific, I want whenever a cell in column B is changed then one cell to the left (column A) gets the row number. 更具体地说,我希望每当更改B列中的一个单元格时,然后左边的一个单元格(列A)就获得行号。 Also I want whenever a cell in column J is changed then one cell to the right (column K) gets today's date. 我也想每当改变J列中的一个单元格时,右边的一个单元格(K列)就会获得今天的日期。

It worked for me for both of them individually but I think I may be doing something wrong using them together. 这对我来说对于他们两个人来说都是独立的,但我认为将它们一起使用可能会做错什么。

Any help will be much appreciated! 任何帮助都感激不尽!

Private Sub AG1(ByVal a_Target As Range)
   If Not Intersect(a_Target, Me.Range("B2:B3000")) Is Nothing Then
      Application.EnableEvents = False
      Cells(a_Target.Row, a_Target.Column - 1) = a_Target.Row
      Application.EnableEvents = True
   End If 
End Sub




Private Sub AG2(ByVal b_Target As Range)
   If Not Intersect(b_Target, Me.Range("J2:J3000")) Is Nothing Then
       Application.EnableEvents = False
       Cells(b_Target.Row, b_Target.Column + 1) = Date
       Application.EnableEvents = True
   End If
End Sub

edit - works now (I also added that column can be referred as letter): 编辑-现在可以工作(我还添加了该列可以称为字母):

Private Sub Worksheet_Change(ByVal Target As Range)


Application.EnableEvents = True

   If Split(Cells(1, Target.Column).Address(True, False), "$")(0) = "B" Then
      Application.EnableEvents = False
      Cells(Target.Row, Target.Column - 1) = Target.Row
      Application.EnableEvents = True

   ElseIf Split(Cells(1, Target.Column).Address(True, False), "$")(0) = "J" Then
       Application.EnableEvents = False
       Cells(Target.Row, Target.Column + 1) = Date
       Application.EnableEvents = True
   End If


End Sub

Copy the code in the Worksheet_Change event and that should fix your issue. 复制代码在Worksheet_Change事件中,这应该可以解决您的问题。 This will trigger every time you enter a value for any cell and will only meet the condition if they intersect the range in the if statement. 每当您输入任何单元格的值时,这都会触发,并且仅当它们与if语句中的范围相交时才满足条件。

Private Sub Worksheet_Change(ByVal Target As Range)

   If Not Intersect(Target, Me.Range("B2:B3000")) Is Nothing Then
      Application.EnableEvents = False
      Cells(Target.Row, Target.Column - 1) = Target.Row
      Application.EnableEvents = True
   End If

   If Not Intersect(Target, Me.Range("J2:J3000")) Is Nothing Then
       Application.EnableEvents = False
       Cells(Target.Row, Target.Column + 1) = Date
       Application.EnableEvents = True
   End If


End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM