How to enter data manually in a cell and the date is automatique in adjacent cell and to change it, request password? - excel

The code returns error messages implying some parts of code are missing yet they are there. E.g With without End With, and of course it's there.
These are two codes that i wrote separately with the aim of combining after making sure that they function well. But it turns out i need some help to get them together.
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.EnableEvents = False
Dim k As Integer
Dim j As Integer
If Target.Column = 4 Then
confirm = MsgBox("Do you wish to confirm entry of this data?" _
& vbCrLf & "You'll not be allowed to change it!", vbYesNo, "confirm Entry")
Select Case confirm
Case Is = vbYes
Dim Cell As Range
With ActiveSheet
.Unprotect Password:="10"
.Cells.Locked = False
For Each Cell In ActiveSheet.UsedRange
For j = 4 To 4
For k = 10 To 60
If Cells(k, j).Value <> "" Then
Cells(k, "C").Value = Date
Cells(k, "C").NumberFormat = "m/d/yyyy"
Else
Cell.Locked = True
End If
Next
.Protect Password:="10"
Case Is = vbNo
Next
Next
Range("C11:C60").Columns.AutoFit
End With
End If
End Select
Application.EnableEvents = True
End Sub
I'm trying to get this code to automatically do the following :
When cell is empty then information can be entered then display date in adjecent cell after the data is in the cell. And when the data needs to be changed request for password with yes/no vba functions.

I cleaned up your code, though haven't tested if it does what you want it to do, it at least compiles:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
Dim k As Integer
Dim confirm As Integer
Dim cell As Range
If Target.Column = 4 Then
confirm = MsgBox("Do you wish to confirm entry of this data?" _
& vbCrLf & "You'll not be allowed to change it!", vbYesNo, "confirm Entry")
Select Case confirm
Case vbYes
With Me
.Unprotect Password:="10"
.Cells.Locked = False
For k = 10 To 60
If .Cells(k, 4).Value <> "" Then
.Cells(k, 3).Value = Date
.Cells(k, 3).NumberFormat = "m/d/yyyy"
End If
Next
.Cells.Locked = True
.Protect Password:="10"
.Range("C11:C60").Columns.AutoFit
End With
End Select
End If
Application.EnableEvents = True
End Sub

Related

Invalid use of property in VBA

I've been following a tutorial on Youtube for an employee manager, It uses a lot of features that i don't need so I've been trying to pick out parts that it need.
I have no experience with VBA or coding so I'm struggling to work out why certain things wont work.
The Screenshots have annotations of the intended results.
Than you in advance
Example and annotations of intended result
Error message
Debug view
Here are my Macros for the buttons and the refresh
Option Explicit
Public EventRow As Long
Public EventCol As Long
Public MapRng As String
Sub Event_SaveNew()
With Sheet6
'check req fields
If Sheet3.Range("g3").Value = Empty Or Sheet3.Range("g5").Value = Empty Then
MsgBox ("Event Name and Event Type are required fields for ANY Event")
Exit Sub
End If
EventRow = .Range("E2000").End(xlUp).Row + 1 'first av row
.Cells(EventRow, 5).Value = Sheet3.Range("b7").Value 'new event id
For EventCol = 6 To 12
.Cells(EventRow, EventCol).Value = Sheet3.Range(.Cells(1, EventCol).Value).Value 'event feild
Next EventCol
End With
With Sheet3
.Range("B2").Value = False 'set new event to false
.Range("B4").Value = Sheet6.Cells(EventRow, 1).Value 'New event ID
Event_Refresh
'reload events
End With
End Sub
Sub Event_Refresh()
Dim LastEventRow As Long
Dim LastFiltRow As Long
With Sheet3
'load Events list into events sheet using adv filter and sort
.Range("f22:m2000").ClearContents 'clear existing events list
LastEventRow = Sheet6.Range("e2000").End(xlUp).Row + 6
Sheet6.Range ("e4:L" & LastEventRow)
End With
End Sub
Sub Event_AddNew()
With Sheet3
.Range("B1").Value = True 'set event load to true
.Range("b2").Value = True 'set new event to true
.Range("J7,j5,g5,g3,f11:j17,g7,g8,j3").ClearContents
.Range("b1").Value = False 'set event load to false
.Range("G3").Select
End With
End Sub
Sub Event_Load()
Dim SelRow As Long
With Sheet3
SelRow = .Range("b9").Value
If .Range("B3").Value = Empty Then
MsgBox "Please select on an Event to display Event details"
Exit Sub
End If
.Range("b1").Value = True 'set empload to true
EventRow = .Range("b3").Value
End With
With Sheet6
For EventCol = 6 To 12
MapRng = Sheet6.Cells(1, EventCol).Value
.Range(MapRng).Value = Sheet6.Cells(EventRow, EventCol).Value 'add maped values
Next EventCol
End With
With Sheet3
.Range("B2").Value = False 'set new event to false
.Range("B1").Value = False 'set event load to false
End With
End Sub
Sub Event_Delete()
If MsgBox("Are you sure you want to DELETE this event?", vbYesNo, "Delete Event") = vbNo Then Exit Sub
With Sheet3
If .Range("B3").Value = Empty Then Exit Sub
EventRow = .Range("B3").Value 'event row
Sheet6.Range(EventRow & ":" & EventRow).EntireRow.Delete
Event_Refresh 'refresh events
End With
End Sub
Sub Event_CancelNew()
With Sheet3
.Range("b2").Value = False
Sheet3.Range("F22").Select
End With
End Sub
And here is the code for the Event log page
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MapRng As Range
Dim FoundMapRng As Range
Dim CellAdd As String
Dim SellRow As Long
'exsisting event change update event tab
If Not Intersect(Target, Range("F3:L17")) Is Nothing And Range("B2").Value = False And Range("B1").Value = False And IsNumeric(Cells(Target.Row, Target.Column + 25).Value) = True And Cells(Target.Row, Target.Column + 25).Value <> Empty Then
Sheet6.Cells(Range("b3").Value, Cells(Target.Row, Target.Column + 25).Value).Value = Target.Value
End If
'update below
CellAdd = Target.Address
SellRow = Range("b9").Value
Set MapRng = Sheet3.Range("EventDataMap")
Set FoundMapRng = MapRng.Find(CellAdd, , xlValues, xlWhole)
If Not FoundMapRng Is Nothing Then Cells(SellRow, FoundMapRng.Column).Value = Sheet6.Cells(Range("b3").Value, Cells(Target.Row, Target.Column + 25).Value).Value
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
'on table selection
If Not Intersect(Target, Range("F22:M2000")) Is Nothing And Range("f" & Target.Row).Value <> Empty Then
Range("b9").Value = Target.Row 'add in selection row
Range("b4").Value = Range("f" & Target.Row).Value 'add event ID
Event_Load
End If
End Sub

Worksheet_Change handling different actions for different columns of a worksheet not looping correctly

In The following worksheet macro, I am attempting to perform different actions, depending on the column selected. In 2 cases the action performed depends on the Column selected and the column value.
For example, if a name is entered in column A, the date is automatically entered in column B.
When a drop down value is entered in Column L, date is entered in Column M. If data in column L = "Fees Received" or "Policy No. Issued" data is copied to another worksheet and the date is entered in column m.
All individual components are working. However not all the time.
I need the macro to identify the column and perform the correct action such that I can move from column to column and the macro to constantly run in the background and working correctly for all selected columns.
Private Sub Worksheet_Change(ByVal Target As Range)
'Dim C As Range, V
Dim answer As Integer
Dim LRowCompleted As Integer
Application.EnableEvents = False
MsgBox "Target Column is " & Target.Column
MsgBox "Target Value is " & Target.Value
If Target.Column = 1 Then
GoTo AddEntryDate
End If
If Target.Column = 12 Then
GoTo AddWorkStatusDate
End If
If (Target.Column = 12 And Target.Value = "Fees Received") Then
GoTo FeesReceived
End If
If (Target.Column = 12 And Target.Value = "Policy No. Issued") Then
GoTo PolicyNoIssued
End If
Exit Sub
AddEntryDate:
'Update on 11/11/2019 -If data changes in column L Activity , insert
'today's date into column M - Date of Activity
Dim WorkRng As Range
Dim rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("A:A"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each rng In WorkRng
If Not VBA.IsEmpty(rng.Value) Then
rng.Offset(0, xOffsetColumn).Value = Now
rng.Offset(0, xOffsetColumn).NumberFormat = "dd/mm/yyyy"
rng.Offset(3, xOffsetColumn).Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
Exit Sub
AddWorkStatusDate:
'Update on 11/11/2019 -If data changes in column L Activity , insert
'today's date into column M - Date of Activity
Dim WorkRng2 As Range
Dim rng2 As Range
Dim yOffsetColumn As Integer
Set WorkRng2 = Intersect(Application.ActiveSheet.Range("L:L"), Target)
yOffsetColumn = 1
If Not WorkRng2 Is Nothing Then
Application.EnableEvents = False
For Each rng2 In WorkRng2
If Not VBA.IsEmpty(rng2.Value) Then
rng2.Offset(0, yOffsetColumn).Value = Now
rng2.Offset(0, yOffsetColumn).NumberFormat = "dd/mm/yyyy"
Else
rng2.Offset(0, yOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
Exit Sub
PolicyNoIssued:
Sheets("Income").Select
LRowCompleted = Sheets("Income").Cells(Rows.Count, "A").End(xlUp).Row '
'Request confirmation from the user, in form of yes or no
answer = MsgBox("Do you want to copy this client to the Income Worksheet?", vbQuestion + vbYesNo)
If answer = vbYes Then
Range("A" & Target.Row & ":A" & Target.Row).Copy
Sheets("Income").Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.EnableEvents = True
Else
MsgBox "This client will not be copied to the Income Worksheet"
Application.EnableEvents = True
End If
Exit Sub
FeesReceived:
'Define last row on Income worksheet to know where to place the row of data
Sheets("Income").Select
LRowCompleted = Sheets("Income").Cells(Rows.Count, "A").End(xlUp).Row
'Request confirmation from the user, in form of yes or no
answer = MsgBox("Do you want to copy this client to the Income Worksheet?", vbQuestion + vbYesNo)
If answer = vbYes Then
Range("A" & Target.Row & ":A" & Target.Row).Copy
Sheets("Income").Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.EnableEvents = True
Else
MsgBox "This client will not be copied to the Income Worksheet"
Application.EnableEvents = True
End If
Application.EnableEvents = True
End Sub
From what I can see, you need to monitor only 2 columns. Rest of your requirements is just subsets of those requirements.
Your code can be re-written as below (UNTESTED) Let me know if you get any error? Also since you are working with Worksheet_Change, you may want to see THIS.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aCell As Range
Dim wsInc As Worksheet
Dim lRow As Long
Dim ans As Variant
On Error GoTo Whoa
Application.EnableEvents = False
'~~> Check if the change happened in Col A
If Not Intersect(Target, Columns(1)) Is Nothing Then
For Each aCell In Target.Cells
With aCell
If Len(Trim(.Value)) = 0 Then
.Offset(, 1).ClearContents
Else
.Offset(, 1).NumberFormat = "dd/mm/yyyy"
.Offset(, 1).Value = Now
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End With
Next
'~~> Check if the change happened in Col L
ElseIf Not Intersect(Target, Columns(12)) Is Nothing Then
Set wsInc = Sheets("Income")
lRow = wsInc.Range("A" & wsInc.Rows.Count).End(xlUp).Row + 1
For Each aCell In Target.Cells
With aCell
If Len(Trim(.Value)) = 0 Then
.Offset(, 1).ClearContents
Else
.Offset(, 1).NumberFormat = "dd/mm/yyyy"
.Offset(, 1).Value = Now
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'~~> Check of the value is Fees Received, Policy No. Issued
If .Value = "Fees Received" Or .Value = "Policy No. Issued" Then
ans = MsgBox("Do you want to copy this client to the Income Worksheet?", vbQuestion + vbYesNo)
If ans = False Then Exit For
wsInc.Range("A" & lRow).Value = Range("A" & aCell.Row).Value
End If
End If
End With
Next
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub

Prevent EventChange Sub running unexpectedly

Advice would be gratefully appreciated. I am developing a spreadsheet using Excel 2016/Windows.
I have written 4 eventchange subroutines and all work well. The VBA Code for a worksheet checks for 4 events. Event 1, 2 and 3 enter today's date in a cell if data is entered in another cell (code not included below)
Code for EventChange works fine, but sometimes works when not expected to!
EventChange4 moves a value from one cell to another if another cell contains the text in Column J is "THIS Month – Payment Due" or "Issued But Not Paid. The second part of this eventchange4 moves a zero value to 2 cells if the data in column j contains text "not going ahead"
I am new to VBA. The problem is that eventchange4 runs for no apparent reason, e.g. copying a cell value in column H down to another cell in column h. How can I modify the code such that that eventchange4 only runs when the data in Column J Changes??? All advice gratefully accepted!!!!
Private Sub Worksheet_Change(ByVal Target As Range)
Call EventChange_1(Target)
Call EventChange_2(Target)
Call EventChange_3(Target)
Call EventChange_4(Target)
End Sub
Sub EventChange_1(ByVal Target As Range)
'Update on 11/11/2019 -If data changes in column L, insert
'today's date into column M
End Sub
Sub EventChange_2(ByVal Target As Range)
'Update on 15/01/2020 -If data changes in column P, insert today's date
'into next Column Q
End Sub
Sub EventChange_3(ByVal Target As Range)
'Update on 15/01/2020 -If data changes in column R, insert today's date
'into next Column S
End Sub
Sub EventChange_4(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
' this works !
If Target.Column = 10 And (Target.Value = "THIS Month – Payment Due" Or Target.Value = "Issued But Not Paid") Then
Range("K" & Target.Row).Value = Range("I" & Target.Row).Value
Range("I" & Target.Row).Clear
MsgBox "Moved Commission Due to Month Paid"
End If
If Target.Column = 10 And (Target.Value = "Not Going Ahead") Then
Range("I" & Target.Row).Value = 0
Range("K" & Target.Row).Value = 0
MsgBox "Moved ZERO to Initial Commisson and Month Paid"
End If
Application.EnableEvents = True
End Sub
Ideally you should update your code so it can properly handle a Target range which is not just a single cell:
Sub EventChange_4(ByVal Target As Range)
Dim rng As Range, c As Range, v
'any part of Target in Column J?
Set rng = Application.Intersect(Target, Me.Columns(10))
If Not rng Is Nothing Then
'have some cells to process...
On Error GoTo haveError
Application.EnableEvents = False
'process each affected cell in Col J
For Each c In rng.Cells
v = c.Value
If v = "THIS Month – Payment Due" Or v = "Issued But Not Paid" Then
Range("K" & c.Row).Value = Range("I" & c.Row).Value
Range("I" & c.Row).Clear
MsgBox "Moved Commission Due to Month Paid"
End If
If v = "Not Going Ahead" Then
Range("I" & c.Row).Value = 0
Range("K" & c.Row).Value = 0
MsgBox "Moved ZERO to Initial Commisson and Month Paid"
End If
Next c
End If
haveError:
Application.EnableEvents = True
End Sub
NOTE: this is assumed to be in the relevant worksheet code module - otherwise you should qualify the Range() calls with a specific worksheet reference.
All your "change" handlers should follow a similar pattern.
Tim apologies. I am new to this and was anxious to get a solution. Thank you for your response. Advice Noted. T
When I attempt to insert or delete a row in the spreadsheet, the VBA code identifies a worksheet event and attempts to run the code. The spreadsheet crashes. I have attempted to add code that will prevent this by checking at the beginning of the module if a row has been inserted or deleted before the other worksheet change event if statements are checked
Thank you
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aCell As Range
Dim wsInc As Worksheet
Dim count As Integer
Dim lRow As Long
Dim ans As Variant
Dim tb As ListObject
On Error GoTo Whoa
Application.EnableEvents = False
Set tb = ActiveSheet.ListObjects(1)
MsgBox Target.Rows.count
If tb.Range.Cells.count > count Then
count = tb.Range.Cells.count
' GoTo Whoa
ElseIf tb.Range.Cells.count < count Then
count = tb.Range.Cells.count
' GoTo Whoa
'~~> Check if the change happened in Col A
ElseIf Not Intersect(Target, Columns(1)) Is Nothing Then
For Each aCell In Target.Cells
With aCell
If Len(Trim(.Value)) = 0 Then
.Offset(, 1).ClearContents
Else
.Offset(, 1).NumberFormat = "dd/mm/yyyy"
.Offset(, 1).Value = Now
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End With
Next
'~~> Check if the change happened in Col L
ElseIf Not Intersect(Target, Columns(12)) Is Nothing Then
Set wsInc = Sheets("Income")
lRow = wsInc.Range("A" & wsInc.Rows.count).End(xlUp).Row + 1
For Each aCell In Target.Cells
With aCell
If Len(Trim(.Value)) = 0 Then
.Offset(, 1).ClearContents
Else
.Offset(, 1).NumberFormat = "dd/mm/yyyy"
.Offset(, 1).Value = Now
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'~~> Check of the value is Fees Received, Policy No. Issued
If .Value = "Fees Received" Or .Value = "Policy No. Issued" Then
ans = MsgBox("Do you want to copy this client to the Income Worksheet?", vbQuestion + vbYesNo)
If ans = False Then Exit For
wsInc.Range("A" & lRow).Value = Range("A" & aCell.Row).Value
End If
End If
End With
Next
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub

Disallow editing a cell once there is an entry

I am trying to build a log book where:
Once the operator enters information that cell should lock.
A date and time for the entry should auto populate.
I have tried several codes I found on bulletin boards, but nothing works.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Application.EnableEvents = False
If Target.Column = 2 Or Target.Column = 3 Then
For i = 2 To 1000
If Cells(i, "B").Value <> " " And Cells(i, "B").Value = " " Then
Cells(i, "A").Value = Date & " " & Time
Cells(i, "A").NumberFormat = "m/d/yyyy h:mm AM/PM"
End If
Next
End If
Range("F:F").EntireColumn.AutoFit
Application.EnableEvents = True
End Sub
In the same article you have a solution:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B:B")) Is Nothing Then
On Error GoTo SafeExit
Application.EnableEvents = False
Dim bc As Range 'no sense in declaring something until we actually need it
For Each bc In Intersect(Target, Range("B:B")) 'deal with every cell that intersects. This is how to handle pastes into more than one cell
If Not IsEmpty(Cells(bc.Row, "B")) Then
Cells(bc.Row, "A").Value = Now 'Now is the equivalent of Date + Time
Cells(bc.Row, "A").NumberFormat = "m/d/yyyy h:mm AM/PM"
End If
Next bc
'Range("F:F").EntireColumn.AutoFit 'this slows things down. you may want to comment this out and just set an apprpriate column width that will handle everything
End If
SafeExit:
Application.EnableEvents = True
End Sub
I just addpat for your case on Range B:B.
Hope it helps

How do I compare absolute difference between column and one target cell, and afterward, sort by Abs diff?

I am trying to create a scoreboard using VBA in Excel. When users click on the button to enter (See image below), they will key in their names, id and numeric answer in a user form (So 3 text boxes for them to fill up).
After the user clicks submit in the userform, the value should be saved in Sheet 1 for collation (take note of the 4,000 in Cell D2, more on it later):
This is the code for the userform:
Private Sub CommandButton1_Click()
If TextBox1.Value = "" Or TextBox2.Value = "" Or TextBox3.Value = "" Then
If MsgBox("Your details are not complete! Do you want to continue?", vbQuestion + vbYesNo) <> vbYes Then
Exit Sub
End If
End If
Worksheets("Sheet1").Select
'Worksheets("Sheet1").Range("A2").Select
ActiveCell = TextBox1.Value
ActiveCell.Offset(0, 1) = TextBox2.Value
ActiveCell.Offset(0, 2) = TextBox3.Value
ActiveCell.Offset(1, 0).Select
Call resetform
End Sub
Sub resetform()
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
UserForm1.TextBox1.SetFocus
End Sub
Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(TextBox3.Value) Then
MsgBox "Only numbers are allowed"
Cancel = True
End If
End Sub
By right, when users click on the submit answer command button, the values will be saved accordingly in Sheet1 with the code above.
However, my issue arises here now. I want to sort the values by absolute differences. I.e I want to compare all the numeric answers in Col C of Sheet1, to the target answer in Cell C3 of Sheet2.:
After calculating the absolute differences, I want to sort the rows according to the absolute differences in Ascending order. This is the code for the sorting:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
Dim test As Variant
Dim calc As Variant
If Not Intersect(Target, Range("C:C")) Is Nothing Then
Application.EnableEvents = False
For i = 1 To Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
calc = Sheet1.Cells(i + 1, "C").Value
test = Sheet2.Cells(3, 3).Value
Sheet1.Cells(i + 1, "D").Value = Abs(test - calc)
Application.EnableEvents = False
Range("A:D").Sort Key1:=Range("D2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
Application.EnableEvents = True
Next i
End If
End Sub
However, when I clear my fields in Sheet1, the 4,000 in Cell D2 appears. (I'm guessing it has to do with the 4,000 in the target answer minusing 0 since the fields are blank.) If I have new entries, and the difference is very huge, the sheet becomes messed up and looks like this:
When I key in another number with a huge absolute difference, the 4,000 is repeated and the previous largest absolute difference is replaced with the new largest absolute difference value. Does anyone know why?
For #Mikku this is the latest error!:
I think this will solve your problem. Looks like you are selecting any other cell before running the Userform, which in turn is the reason for those 2 blank rows. Try the Below and tell me if it's still happening.
Change:
Worksheets("Sheet1").Select
'Worksheets("Sheet1").Range("A2").Select
ActiveCell = TextBox1.Value
ActiveCell.Offset(0, 1) = TextBox2.Value
ActiveCell.Offset(0, 2) = TextBox3.Value
ActiveCell.Offset(1, 0).Select
With:
Dim last As Long
With Worksheets("Sheet1")
last = .Cells(.Rows.Count, "A").End(xlUp).row
.Range("A" & last + 1).Value = TextBox1.Value
.Range("B" & last + 1).Value = TextBox2.Value
.Range("C" & last + 1).Value = TextBox3.Value
End With
Change the Worksheet Event Code to this: (Untested)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
Dim test As Variant
Dim calc As Variant
If Not Intersect(Target, Range("C:C")) Is Nothing Then
Application.EnableEvents = False
test = Worksheets("Sheet2").Cells(3, 3).Value
With Worksheets("Sheet1")
For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
calc = .Cells(i, "C").Value
.Cells(i, "D").Value = Abs(test - calc)
Next i
.Range("A:D").Sort Key1:=.Range("D2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
Application.EnableEvents = True
End With
End If
End Sub
Demo:
Updated Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
Dim test As Variant
Dim calc As Variant
If Not Intersect(Target, Range("E:E")) Is Nothing Then
Application.EnableEvents = False
Dim lst As Long
test = Worksheets("Target Answer").Cells(3, 3).Value
With Worksheets("Consolidation")
lst = .Cells(.Rows.Count, "C").End(xlUp).Row
For i = 3 To lst
calc = .Cells(i, "E").Value
.Cells(i, "F").Value = Abs(test - calc)
Next i
.Range("C2:F" & lst).Sort Key1:=.Range("F3"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
Application.EnableEvents = True
End With
End If
End Sub

Resources