工作簿_新工作表Excel VBA错误消息

50few1ms  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(141)

我向Excel ThisWorkbook中添加了代码,试图向Excel工作簿中创建的每个工作表添加sheetwork_change代码。我运行该代码并收到以下错误消息:编译错误:找不到方法或数据成员。
有人知道这是什么吗?

Private Sub Workbook_NewSheet(ByVal Sh As Object)
    Dim ws As Worksheet
    Set ws = Sh
    
    ' Add Worksheet_Change event to new sheet
    Dim code As String
    code = "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf & _
           "    If Not (Application.Intersect(Range(""A1:E19""), Target) Is Nothing) Then" & vbCrLf & _
           "        MsgBox ""Cell "" & Target.Address & "" has changed."", vbInformation, ""Test""" & vbCrLf & _
           "    End If" & vbCrLf & _
           "End Sub"
    
    With ws.CodeModule
        .InsertLines 2, code
    End With
End Sub
juzqafwq

juzqafwq1#

您的代码可以通过一个小的修复来工作:

Private Sub Workbook_NewSheet(ByVal Sh As Object)
    Dim ws As Worksheet
    Set ws = Sh
    
    ' Add Worksheet_Change event to new sheet
    Dim code As String
    code = "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf & _
           "    If Not (Application.Intersect(Range(""A1:E19""), Target) Is Nothing) Then" & vbCrLf & _
           "        MsgBox ""Cell "" & Target.Address & "" has changed."", vbInformation, ""Test""" & vbCrLf & _
           "    End If" & vbCrLf & _
           "End Sub"
    
    With ThisWorkbook.VBProject.VBComponents(Sh.CodeName).CodeModule
        .InsertLines 2, code
    End With
End Sub

相关问题