通过其他代码向工作表事件添加代码

时间:2017-11-02 16:14:23

标签: excel excel-vba vba

我有以下代码,我想从同一工作簿中的模块中的代码添加到Sheet3的BeforeDoubleClick事件。看起来我可以执行this之类的操作,但这涉及为我的代码的每一行执行.InsertLines。还有更好的方法吗?

看起来我也可以构建一个string of my code,感觉更直接。我只有41行,所以我猜它不是那么糟糕。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

Dim acct As String
Dim month As String
Dim ws2 As Worksheet
Dim lastRow As Long

Cancel = True
Set ws2 = ThisWorkbook.Worksheets("Sheet2")

With Target.Worksheet
    acct = .Cells(1, Target.Column).Value
    month = .Cells(Target.Row, 1).Value
End With

With ws2

    lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

    For i = 1 To lastRow
        If .Cells(i, 3).Value = acct Then Exit For
    Next

    For k = i To lastRow
        If .Cells(k, 6).Value = month Then Exit For
    Next

    For m = k To lastRow
        If .Cells(m, 6).Value <> month Then
        s = m
        Exit For
        End If
    Next

    ws2.Activate
    .Range(.Cells(k, 10), .Cells(s - 1, 12)).Select
    Selection.Activate

End With

End Sub

解决:我所要做的就是添加

If Sh.Name <> "Sheet3" Then Exit Sub

到我的代码顶部。感谢SJR。

0 个答案:

没有答案