此代码与.xlsm文件相关联,例如X
。当我打开X
文件,然后打开第二个文件Y
时,来自X
的宏也会在{"删除&#34}时进入Y
。或"退格"在Y
中按下。此外,如果我打开X
和Y
然后关闭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
答案 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