Excel worksheet_change event

别来无恙 提交于 2019-12-24 14:41:38

问题


I am wondering if you could help me with the worksheet_Change for two different targets.

MY code is the following:

Private Sub Worksheet_Change(ByVal Target As Range)

        If Intersect(Target, Range("A1:A50")) Is Nothing Then Exit Sub        
             Range("A1:A50").Copy ThisWorkbook.Sheets(2).Range("B1")

 End Sub

And it is working, whenever anytjing is updated in column A it is updated and copied in column B(worksheet 2). Now the problem I have is that i want to add another target, B1:B50, and only If that target has the word SUM in it, it should copy and update. The problem is that it is copying but NOT updating anything. My code for that is:

Private Sub Worksheet_Change(ByVal Target As Range)

        If Intersect(Target, Range("A1:A50, B1:B50")) Is Nothing Then Exit Sub    
    If Target.Address = "TOTAL" Then
             Range("A1:A50").Copy ThisWorkbook.Sheets(2).Range("B1")
       end if
 End Sub

What shoudl i do?


回答1:


I think you're confused on what Target represents. Target, in the scope of a Worksheet_Change event is the cell(s) being changed.

Also, the Target.Address will never be "TOTAL", so this logic will not work:

If Target.Address = "TOTAL"

With that in mind, I would do something like this. Create a separate procedure for each range (column A or B). Then use the Worksheet_Change event to determine which procedure to call on:

Private Sub Worksheet_Change(ByVal Target As Range)

 If Intersect(Target, Range("A1:A50, B1:B50")) Is Nothing Then Exit Sub    
 If Target.Column = 1 Then Call RangeA(Target)
 If Target.Column = 2 Then Call RangeB(Target)
End Sub

Sub RangeA(Target as Range)
    Range("A1:A50").Copy ThisWorkbook.Sheets(2).Range("B1")
End Sub

Sub RangeB(Target As Range)

    'Here, you put the code that you want to run when Target is in column B

End Sub

Since I'm not exactly sure what you intend to do with Column B, I left the RangeB procedure empty for now. You can modify that procedure to do whatever you want, based on the target change in range B1:B50.




回答2:


How does column B get populated?

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("A1:A50")) Is Nothing Then
        Range("A1:A50").Copy ThisWorkbook.Sheets(2).Range("B1")
    End If

    If Not Intersect(Target, Range("B1:B50")) Is Nothing Then
        If Target = "Total" Then
            MsgBox Target.Address    'do something here
        End If
    End If

End Sub


来源:https://stackoverflow.com/questions/29461638/excel-worksheet-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!