简体   繁体   中英

How do I combine two private Worksheet_Change subs into one in VBA?

I currently have this code :

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim lastrow As Long
    Dim rngList As Range

    lastrow = Cells(Rows.Count, "A").End(xlUp).Row

    Set rngList = Range("AB3").CurrentRegion

    If Target.Cells.Count > 1 Then Exit Sub

    On Error Resume Next

    If Not Intersect(Target, Range("B18:B19")) Is Nothing Then  ' user is in column-A
        Target.Value = Application.WorksheetFunction.VLookup(Target.Value, rngList, 2, False)
    End If

    Set rngList = Nothing
End Sub

and

Private Sub Worksheet_Change(ByVal Target As Range)

Dim lastrow As Long
Dim rngList As Range

lastrow = Cells(Rows.Count, "A").End(xlUp).Row

Set rngList = Range("AC3").CurrentRegion

If Target.Cells.Count > 1 Then Exit Sub

On Error Resume Next

If Not Intersect(Target, Range("B10:B11")) Is Nothing Then  ' user is in column-A
    Target.Value = Application.WorksheetFunction.VLookup(Target.Value, rngList, 2, False)
End If

Set rngList = Nothing

End Sub

I would like to combine them so that I can use both, but I don't know how to do so without conflict, any help would be appreciated, thank you.

If I understand you correctly this should do the trick you were trying to do:

Private Sub Worksheet_Change(ByVal Target As Range)

    WorksheetChanged Target, Range("AC3").CurrentRegion, Range("B10:B11")
    WorksheetChanged Target, Range("AB3").CurrentRegion, Range("B18:B19")

End Sub

Private Sub WorksheetChanged( ByVal Target As Range, ByVal rngList As Range, ByVal intersectRng As Range )

    Dim lastrow As Long

    lastrow = Cells(Rows.Count, "A").End(xlUp).Row

    If Target.Cells.Count > 1 Then Exit Sub

    On Error Resume Next

    If Not Intersect(Target, intersectRng) Is Nothing Then  ' user is in column-A
        Target.Value = Application.WorksheetFunction.VLookup(Target.Value, rngList, 2, False)
    End If

    Set rngList = Nothing
End Sub

Here you have a private function which gets the Ranges as Parameters. You can call this function as often as you want (though Excel might become a bit slow if you call it too much in the Worksheed_Change Sub).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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