在哪里放我的代码 - VBA

时间:2014-05-12 16:07:42

标签: excel vba

我的工作表上运行了代码。此代码包含两个子例程。但我想在我的所有表格中运行此代码,我想知道什么是最好的方法。

正在运行的总代码如下:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim Rng As Range
Set Rng = Range(Cells(3, 6), Cells(500, 7))
Dim Intersection
Set Intersection = Application.Intersect(Target, Rng)

If Target.Cells.Count = 1 Then
    If Not Intersect(Target, [B2]) Is Nothing Then _
        Range("E:E").Find(vbNullString, [E3], , , , xlNext).Select
End If

If Not Intersection Is Nothing Then
    If IsNumeric(Selection.Value) And Selection.Value <> "" Then
        If (GetAsyncKeyState(vbKeyRButton)) Then 'right mouse button
            Selection.Value = (Selection.Value + 1)
            Cells(Selection.Row, 1).Select
        End If
    End If
End If

End Sub

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Dim Rng As Range
    Set Rng = Range(Cells(3, 6), Cells(500, 7))
    Dim Intersection
    Set Intersection = Application.Intersect(Target, Rng)

    If Not Intersection Is Nothing Then
    Cancel = True
    End If
End Sub

如果有人能给我提示,我们将不胜感激!

3 个答案:

答案 0 :(得分:1)

将您的代码放入模块中。您可以点击以下链接。

http://www.contextures.com/xlvba01.html

答案 1 :(得分:1)

将代码放在其他位置会更复杂。如果您将代码放在一个模块中(这是正确的移动),您将需要告诉它也可以在其他工作表上运行。您可以编写代码以应用于Worksheet对象代码模块中任何打开或关闭的工作簿中的任何工作表。这都是关于如何写的。

您是否在代码中使用MeActiveSheet等作品?这是红旗,无论你放在哪里,结果都可能不是你想要的。

答案 2 :(得分:0)

如果希望更改事件对工作簿中的所有工作表有效,请将代码放在ThisWorkbook模块中并使用Workbook_SheetChange事件。在任何工作表中更改任何单元格时,将触发此事件。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

End Sub
相关问题