Forum Discussion
Excel VBA Object Variable or With Block Variable Not Set Error
Good morning! I fixed that error, but now I'm having an error with a different section of my code. There is a section on the worksheet module to prompt the user when they attempt to delete data in Column C (starting in C9 to lastrow), but I'm having a issue with the undo function. It deletes the row just fine when I select 'Yes', but when I select 'Cancel' it gives me 'Run-time error '1004': Method 'Undo' of object '_Application' failed'. Is there a different method I could use or am I using '.undo' incorrectly? The specific piece of code is below (starts at 24) and the Google Drive is located https://gcc02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F1-QZdsQdKN62pqMkntGFYE1EKg2pyREOv%2Fedit%3Fusp%3Ddrivesdk%26ouid%3D102479528135295286349%26rtpof%3Dtrue%26sd%3Dtrue&data=05%7C02%7Cshaun.beauchem%40state.mn.us%7C3ffd8f51ec0140faf32408dd5287ab81%7Ceb14b04624c445198f26b89c2159828c%7C0%7C0%7C638757464832222558%7CUnknown%7CTWFpbGZsb3d8eyJFbXB0eU1hcGkiOnRydWUsIlYiOiIwLjAuMDAwMCIsIlAiOiJXaW4zMiIsIkFOIjoiTWFpbCIsIldUIjoyfQ%3D%3D%7C0%7C%7C%7C&sdata=DQQGsqrey1ybFpcWsfD%2FpvEoJEARIYVOK33BAm7ut8E%3D&reserved=0.
Option Explicit
Private Const WARNING_MESSAGE As String = "Warning: You are attempting to {0} data." & vbNewLine & _
"That is not allowed in this spreadsheet. Please press 'ESC' to return to your work."
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastRow As Long
Dim intersectRange As Range
Dim YesNo As VbMsgBoxResult
On Error GoTo ErrorHandler
lastRow = Cells(Rows.Count, "C").End(xlUp).Row
Set intersectRange = Intersect(Target, Me.Range("C9:C" & lastRow))
If Not Intersect(Target, Me.Range("C9:C" & lastRow)) Is Nothing Then
Application.EnableEvents = False
Me.Unprotect "123456"
UpdateCellLockStatus Target
Me.Protect "123456", UserInterfaceOnly:=True, AllowFiltering:=True, AllowSorting:=True
End If
If Not intersectRange Is Nothing Then
If IsEmpty(Target) Then ' Content was deleted
YesNo = MsgBox("Warning: You are attempting to delete data in Column C." & vbNewLine & _
"This action will clear the entire row. Do you want to proceed?", vbOKCancel)
If YesNo = vbOK Then ' If OK clicked
With Application
.ScreenUpdating = False
.EnableEvents = False
Target.EntireRow.Delete ' Delete data in Column C
.ScreenUpdating = True
.EnableEvents = True
End With
ElseIf YesNo = vbCancel Then ' If Cancel clicked
With Application
.EnableEvents = False
.Undo
.EnableEvents = True
End With
End If
End If
End If
ExitSub:
Application.EnableEvents = True
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical, "Error"
Resume ExitSub
End Sub
Calling UpdateCellLockStatus disables Undo.