我可以在“此工作簿”下有多个事件代码吗?

时间:2014-08-15 16:22:32

标签: excel vba excel-vba

我有这两个代码:

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Application.ScreenUpdating = False
For Each Value In Target.Columns
    Columns(Value.Column).ColumnWidth = 8.43
    Worksheets(Sh.Name).Columns(Value.Column).AutoFit
Next Value
Application.ScreenUpdating = True
End Sub

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
    If Not Target.Cells.Count = 1 Or Target.Row = 1 Then Exit Sub
    If Target.Offset(1, 0) = "" Then
        Target.Offset(-1, 0).Copy
        Target.PasteSpecial Paste:=xlPasteFormats
        Application.CutCopyMode = False
    End If
    Application.EnableEvents = True
End Sub

这两段代码工作得很好但事情是我不能让它们一起工作这两个代码应该放在excel中的“This Workbook”对象下所以我一直试图找到一种方法工作我明白你应该只在工作簿中有一个事件代码,但有一个“解决方法”,有人建议如下:

    Private Sub Worksheet_Change(ByVal Target As Range)
    Call Macro1(Target)
    Call Macro2(Target)
End Sub

Sub Macro1(ByVal Target As Range)
    If Target.Column = 1 And Target.Offset(1, 0) = "" Then
        Target.Offset(-1, 0).Copy
        Target.PasteSpecial Paste:=xlPasteFormats
        Application.CutCopyMode = False
    End If
End Sub

Sub Macro2(ByVal Target As Range)
    Application.ScreenUpdating = False
For Each Value In Target.Columns
    Columns(Value.Column).ColumnWidth = 8.43
    Worksheets(Sh.Name).Columns(Value.Column).AutoFit
Next Value
Application.ScreenUpdating = True
End Sub

但它不起作用没有触发任何事件因此我没有发生任何事情,我一开始认为这是不可能的,但是当有人建议这一点起初它有意义但它不起作用但我仍然看到了我希望紧紧抓住希望,因为我不知道是谁让它发挥作用。

是否可以让这两个代码在同一个工作簿上运行?

2 个答案:

答案 0 :(得分:0)

这些事件需要位于Sheet对象下,而不是工作簿。请注意,从下拉列表中,当您进入" thisWorkbook"代码部分,没有"更改"事件。您还需要将函数命名为Private Sub Worksheet_Change(ByVal Target As Range)

答案 1 :(得分:0)

到目前为止,我已经尝试了这个,现在还在努力

    Private Sub Worksheet_Change(ByVal Target As Range)
    Call Macro1(Target)
    Call Macro2(Target)
End Sub

Sub Macro1(ByVal Target As Range)
    Application.EnableEvents = False
    If Not Target.Cells.Count = 1 Or Target.Row = 1 Then Exit Sub
    If Target.Offset(1, 0) = "" Then
        Target.Offset(-1, 0).Copy
        Target.PasteSpecial Paste:=xlPasteFormats
        Application.CutCopyMode = False
    End If
    Application.EnableEvents = True
End Sub

Sub Macro2(ByVal Target As Range)
    Application.ScreenUpdating = False
For Each Value In Target.Columns
    Columns(Value.Column).ColumnWidth = 8.43
    ActiveSheet.Columns(Value.Column).AutoFit
Next Value
Application.ScreenUpdating = True
End Sub