避免在另一个Excel文件中运行宏

时间:2015-04-08 16:18:31

标签: excel vba private-methods

此代码与.xlsm文件相关联,例如X。当我打开X文件,然后打开第二个文件Y时,来自X的宏也会在{"删除&#34}时进入Y。或"退格"在Y中按下。此外,如果我打开XY然后关闭X,但Y仍然打开 - 如果我按"删除"或"退格"在Y中,X文件将自动打开。所以,我想避免这种情况,我希望X中的代码只在X内运行。希望它不会太混乱!

Private Sub Worksheet_Change(ByVal Target As Range)

Dim TestCell
Dim RE As Object
Dim REMatches As Object
Dim Cell1_1 As String
Dim Today As String
Dim Cell As String

ThisRow = Target.Row

With Worksheets("Input")
Application.OnKey "{DELETE}", "CleanCell1_1"

Application.OnKey "{BACKSPACE}", "CleanCell1_1"
End With

If Target.Column = 9 Then

Application.ScreenUpdating = False

ActiveSheet.Unprotect
Columns("I:I").Columns.AutoFit
Sheets("Input").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True
    Sheets("Input").EnableSelection = xlUnlockedCells

Sheets("Chart").Unprotect
Sheets("Chart").Columns("B:B").Columns.AutoFit
Sheets("Chart").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
Sheets("Chart").EnableSelection = xlNoRestrictions

Application.ScreenUpdating = True

End If

If Target.Column = 10 Then

Set RE = CreateObject("vbscript.regexp")

With RE
    .MultiLine = False
    .Global = False
    .IgnoreCase = True
    .Pattern = "[G,g,Y,y,R,r]"
End With

For Each TestCell In Target.Cells

Set REMatches = RE.Execute(TestCell.Value)

If REMatches.Count > 0 And Len(Target.Value) = 1 Then
    If Len(Cells(1, 1).Value) = 1 Then
        Today = Now()
        Cell1_1 = Sheets("Input").Cells(1, 1).Value
        Range("K" & ThisRow) = Cell1_1 + ": " + Format(Today, "ddmmmyy")
    End If

ElseIf Target.Value <> vbNullString Then
     Row = Target.Row
     Cells(Row, 10).Value = vbNullString
     MsgBox "Please, type only:" & vbNewLine & vbNewLine & "G for Green" & vbNewLine & "Y for Yellow" & vbNewLine & "R for Red"

End If

Next

End If

End Sub

1 个答案:

答案 0 :(得分:0)

当X工作簿处于活动状态/未激活时,我将激活/取消激活Application.OnKey
像这样:
在ThisWorkbook中:

Private Sub Workbook_Activate() 
    Application.OnKey "{DELETE}", "CleanCell1_1"
    Application.OnKey "{BACKSPACE}", "CleanCell1_1"
End Sub

Private Sub Workbook_Deactivate() 
    Application.OnKey "{DELETE}", ""
    Application.OnKey "{BACKSPACE}", ""
End Sub