vba - 复制和粘贴无意中触发 Worksheet_Change sub
问题描述
当列“P”取值“x”时,我遇到了“Worksheet_Change”子问题,该子将整行复制并粘贴到第二个工作表(“已完成”)中。它的内容如下:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
'If Cell that is edited is in column P and the value is x then
If Target.Column = 16 And Target.Value = "x" Then
'Define last row on completed worksheet to know where to place the row of data
LrowCompleted = Sheets("Completed").Cells(Rows.Count, "A").End(xlUp).Row
'Copy and paste data
Range("A" & Target.Row & ":P" & Target.Row).Copy Sheets("Completed").Range("A" & LrowCompleted + 1)
'Delete Row from Project List
Range("A" & Target.Row & ":P" & Target.Row).Delete xlShiftUp
End If
Application.EnableEvents = True
End Sub
子程序本身工作正常,但如果我在工作表中的任何位置复制和粘贴,子程序就会被激活,并且我粘贴的行会发送到我的“已完成”工作表。
到目前为止,我一直在玩“if-clause”,但没有任何运气。例如:
If Not Target.Column = 16 And Target.Value = "x" Is Nothing Then
我担心我错过了显而易见的事情,我很感激任何帮助。
谢谢并恭祝安康
PMHD
解决方案
谢谢,吉普德。
由于 Target 引用了多个单元格,因此出现了问题。通过排除 Target.Count > 1 的情况来修复它。
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
'Exclude all cases where more than one cell is Target
If Target.Count > 1 Then
'If Cell that is edited is in column P and the value is x then
ElseIf Target.Column = 16 And Target.Value = "x" Then
'Define last row on completed worksheet to know where to place the row of data
LrowCompleted = Sheets("Completed").Cells(Rows.Count, "A").End(xlUp).Row
'Copy and paste data
Range("A" & Target.Row & ":P" & Target.Row).Copy Sheets("Completed").Range("A" & LrowCompleted + 1)
'Delete Row from Project List
Range("A" & Target.Row & ":P" & Target.Row).Delete xlShiftUp
End If
Application.EnableEvents = True
End Sub
推荐阅读
- java - JavaEE 8、Tomcat 8.5、错误状态 404
- php - 函数中的 $_SESSION 变量未传递到下一页
- java - 使用 Okio 的圆形 BufferedSink
- php - 如果使用 PHP 登录,如何允许用户查看 HTML 页面
- java - 2D 空间中的 3D 透视图
- botframework - 由后端每个用户为 Botframework 提供的短语列表
- r - R传单情节船方向
- android - 在最小化应用程序并重新打开时调用 Camera.release() 后正在使用相机
- server - 使用 gsm a6 的 Arduino 程序中的错误主机链接
- actionscript-3 - AS3:创建 BitmapData 的着色副本的最有效方法