excel vba worksheet_change事件无法指定工作表名称

azpvetkf  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(236)

我想为工作簿事件分配sheetname(Sh)和Column range(Target),当工作表中B列的“main”值发生变化时,运行宏Next()

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
   Sh = "main"
   Target = Sh.Range("B:B")
   Next()
End Sub

Sh="main"上给我一个错误,它是否会在任何列中的任何单元格上运行发生更改?但我需要显式“主”工作表,列B(任何单元格)更改事件驱动宏?它甚至可能在VBA中?

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
   Application.EnableEvents=False
   Set Sh = Worksheets("main")
   Set Target = Sh.Range("B:B")
   Next()
   Application.EnableEvents=True
End Sub

当更改主工作表中的任何单元格时,名为Next的子过程将运行。但是,我只需要更改B列中的单元格,当发生时,仅然后Next子过程将运行

62lalag4

62lalag41#

1.避免使用Next作为过程名。
1.您可以使用Sh.Name检查相关工作表中是否发生了更改。
1.在使用Workbook_SheetChangeWorksheet_Change或类似的方法来关闭事件时,建议引入错误处理。
这就是你想要的吗?

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
   
    On Error GoTo Whoa
   
    If UCase(Trim(Sh.Name)) = "MAIN" Then
        If Not Intersect(Target, Sh.Columns(2)) Is Nothing Then
            '~~> Change this to the relevant procedure name
            MyProcedureName
        End If
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Sub MyProcedureName()
    MsgBox "Hello World"
End Sub

另一种方法也是一样的

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
        
    On Error GoTo Whoa
       
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Main")
   
    If Sh.Name = ws.Name Then
        If Not Intersect(Target, ws.Columns(2)) Is Nothing Then
            '~~> Change this to the relevant procedure name
            MyProcedureName
        End If
    End If
Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Sub MyProcedureName()
    MsgBox "Hello World"
End Sub

相关问题