Creating Error Message when changing value of particular cell and restore previous value VBA

totesbotes

New Member
Joined
Jan 29, 2022
Messages
2
Office Version
  1. 365
Platform
  1. Windows
I am trying to create a code using vba whereby I want to make a certain cell B2 read-only and unchangeable when session is unlocked (I have a lock and unlock module for later whereby locked disallow editing and unlocked allows editing).

The code aims to give an error message and restore the cell to the previous value before edits are made when session is locked.

Problem: However, currently the results from this code successfully gave an error message when edit is done when locked BUT made the cell blank after the error message when I actually want it to restore to the previous value before edit was made

Please help if you know what went wrong and thank you in advance

VBA Code:
Public locked As Boolean
Dim oldValue As Variant

Private Sub worksheet_SelectionChange(ByVal Target As Range)
oldValue = Target.Value
End Sub

Private Sub worksheet_Change(ByVal Target As Range)

If Target.Row = 2 And Target.Column = 2 Then
If locked Then
If Target.Value <> oldValue Then
Target.Value = oldValue
MsgBox "You are not allowed to edit!"
End If
End If
End If

End Sub
VBA Code:
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
See if this does what you want:
VBA Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address(0, 0) <> "B2" Then Exit Sub
    If Target <> "" Then
         MsgBox "You are not allowed to edit!"
        Range("A1").Select
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,257
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top