The problem occurs when I am pasting values into multiple cells on that row that are not in column B!
I get an error that should not even be occurring due to the fact that I was not even deleting anything from the table.
Curiously, I can paste single values, for example, I can paste in C35, D35, E35 and F35 individually with no error. But if I do it all at once, I get an error.
I can clarify
why you are getting that error.
Suppose that you are pasting "red", 2, "", 5 into C35:F35 at once.
Clearly that will trigger your code.
Ignoring the Debug.Print line (I think you only have that to try to find what is going wrong) the first line encountered is
Rich (BB code):
If Target.Column = 2 And Target.Row > 1 And Target.Value = "" Then
Now, how can the code evaluate that red bit? We are trying to evaluate if the 'Target' has a value of "", but the target is
four cells, all with different values. In summary, Target.Value is meaningless if there is more than one cell, hence the code throws an error.
Some other comments about your code:
- The
DeleteRows (ProjectName) line is too far down. It will run every time the Worksheet_Change code is triggered, whether or not you have deleted anything in column B.
- In the code, you ask the user if they really want to delete. If they answer 'No', your code doesn't delete the row but it does leave the column B value deleted. Is that what you want to happen or do you want the deleted value restored?
- This isn't an error, but the line
Rows(ActiveCell.Row).EntireRow.Delete does not require the 'EntireRow' part as 'Rows(ActiveCell.row)' already is an entire row.
Here is a modified version of your code that addresses at least some of the issues above.
At this stage I have made 2 assumptions:
i) That you already have the code to deal with deletion in the other sheet via the
DeleteRows (ProjectName) call.
ii) That you will be deleting at most one value at a time from column B
Anyway, see if this nudges you in the right direction.
Rich (BB code):
Private Sub Worksheet_Change(ByVal Target As Range) '_Change creates the variable as a target, transferred as a value to "ProjectName"
Dim ans As Integer
Dim ProjectName As String
Dim Changed As Range
Set Changed = Intersect(Target, Columns(2), Rows("2:" & Rows.Count))
If Not Changed Is Nothing Then
If Changed.Cells.Count = 1 Then
If Changed.Value = "" Then
ans = MsgBox("Are you sure you want to Delete......This cannot Be Undone !!!", vbYesNo)
If ans = vbYes Then
With Application
.EnableEvents = False ' freeze WorkSheetChange event since you're about to UNDO a change
.Undo ' undo the change
ProjectName = Changed.Value ' assign the deleted-undone value in to YYY
Rows(Changed.Row).Delete ' delete that row
.EnableEvents = True ' re-enable all events
End With
MsgBox ProjectName & " has been deleted." ' now you have that value in ProjectName
DeleteRows (ProjectName) 'Gives sub-routine "DeleteRows" the company name
End If
End If
End If
End If
End Sub