Excel vba - Disable paste in multiple cells - excel

I am writing code which compares date entered in one column to date in another column. An error message is displayed if the entry violates data validation rules.
Also, I have disabled cut-paste operation and ctl+d.
Data Validation rules:
Enter valid date between 01/01/1900 and 12/31/9999
Date value in Column AP should be greater than Column AO.
But, when a user copies a cell, selects multiple cells in the target column and pastes, then data validation doesn't trigger at all. Below is the screenshot:
The below code handles single cell operations like copying a cell and paste in another cell but not able to handle when a user selects more than one cell and pastes.
Please help me understand as what is wrong with my code. Thank you!
Here is my code:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo ErrorHandler
Dim lstrow As Long
lstrow = Range("A" & Rows.Count).End(xlUp).Row
If Intersect(Target, Range("AP5:AP" & lstrow - 1)) Is Nothing Then Exit Sub
If Target.Value <> "" And Target.Value <= Range("AO" & Target.Row) Then
Application.EnableEvents = False
Target.Value = ""
MsgBox ("The date you have entered is either not in correct format OR less than date in column AO")
Else: Target.NumberFormat = "dd-mmm-yyyy"
End If
ErrorExit:
Application.EnableEvents = True
Exit Sub
ErrorHandler:
Debug.Print Err.Number & vbNewLine & Err.Description
Resume ErrorExit
End Sub
I tried the below code but it didn't work.
if Target.cells.count > 1 then
msgbox("Select a single cell to paste")
ActiveCell.Select
end if
'========================================================================
I have encountered another issue. Now, I want to evaluate one more column in the same worksheet under worksheet_change event. But, code for only one column is getting evaluated and not the other column.
Please advise.
Here is my updated code:
Private Sub Worksheet_Change(ByVal Target As Range)
'Added to define the last row by locating the text string (blank)
On Error GoTo ErrorHandler
Dim lstrow As Long
'ActiveRow = ActiveCell.Row
lstrow = Range("A" & Rows.Count).End(xlUp).Row
If Intersect(Target, Range("AP5:AP" & lstrow)) Is Nothing Then Exit Sub
If Target.Cells.Count > 1 Then
Application.EnableEvents = False
Application.Undo
MsgBox "Select only single cell to paste"
ActiveCell.Select
Application.CutCopyMode = False
Application.EnableEvents = True
Exit Sub
End If
If Target.Value <> "" And Target.Value <= Range("AO" & Target.Row) Then
Application.EnableEvents = False
Target.Value = ""
MsgBox ("The date you have entered is either not in correct format OR less than Column AO")
Else: Target.NumberFormat = "dd-mmm-yyyy"
Application.EnableEvents = True
Exit Sub
End If
'----------------------------------------------------------------------------------
If Intersect(Target, Range("AL5:AL" & lstrow)) Is Nothing Then Exit Sub
If Target.Cells.Count > 1 Then
Application.EnableEvents = False
Application.Undo
MsgBox "Select only single cell to paste"
ActiveCell.Select
Application.CutCopyMode = False
Application.EnableEvents = True
Exit Sub
End If
If Target.Value <> "" And Target.Value <= Range("AK" & Target.Row) Then
Application.EnableEvents = False
Target.Value = ""
MsgBox ("The value you entered is less than the value in column AK")
Else: Target.NumberFormat = "0.00"
Application.EnableEvents = True
Exit Sub
End If
'----------------------------------------------------------------------------------
ErrorExit:
Application.EnableEvents = True
Exit Sub
ErrorHandler:
Debug.Print Err.Number & vbNewLine & Err.Description
Resume ErrorExit
End Sub
Can we evaluate two different ranges in the same worksheet_change event?
screenshot of the worksheet after the code is run:

After the line
If Intersect(Target, Range("AP5:AP" & lstrow - 1)) Is Nothing Then Exit Sub
Try inserting this additional checking:
If Target.Cells.Count > 1 Then
Application.EnableEvents = False
Application.Undo
msgBox "entering many cells simultaneously in column AP is not allowed"
Application.EnableEvents = True
Exit Sub
End If

Related

combine 2 worksheet_change

what am I doing wrong here...please help, thanks PG
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ValidatedCells As Range
Dim ValidatedCells2 As Range
Dim Cell As Range
Set ValidatedCells = Intersect(Target, Target.Parent.Range("G:G"))
Set ValidatedCells2 = Intersect(Target, Target.Parent.Range("H:H"))
Application.EnableEvents = False
If Not ValidatedCells Is Nothing Or Not ValidatedCells2 Is Nothing Then
For Each Cell In ValidatedCells
If Not Len(Cell.Value) <= 20 Then
MsgBox "The Name """ & Cell.Value & _
""" inserted in " & Cell.Address & _
" in column G was longer than 20. Undo!", vbCritical
Application.Undo
End If
Next Cell
For Each Cell In ValidatedCells2
If Not Len(Cell.Value) <= 50 Then
MsgBox "The Name """ & Cell.Value & _
""" inserted in " & Cell.Address & _
" in column H was longer than 50. Undo!", vbCritical
Application.Undo
Next Cell
Exit Sub
End If
Application.EnableEvents = True
End Sub
I tried above and not sure if it is the syntax or if the loop statements are incorrect, please help
A few issues in your code - after calling Undo there's no point in continuing, so you can just exit at that point. Needs some error handling to make sure Events are not left turned off.
I'd maybe do something like this:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo done
If TooLong(Intersect(Target, Me.Range("G:G")), 20) Then GoTo done
If TooLong(Intersect(Target, Me.Range("H:H")), 50) Then GoTo done
done:
If Err.Number <> 0 Then MsgBox Err.Description 'in case of error
Application.EnableEvents = True
End Sub
'If any cell in range `Monitored` has content longer than `maxLen`,
' call Undo and return True
Function TooLong(Monitored As Range, maxLen As Long) As Boolean
Dim c As Range
If Not Monitored Is Nothing Then
For Each c In Monitored.Cells
If Len(c.Value) > maxLen Then
MsgBox "The Name """ & c.Value & """ inserted in " & c.Address & _
" in column was longer than " & maxLen & ". Undo!", vbCritical
Application.EnableEvents = False
Application.Undo
TooLong = True
Exit Function
End If
Next c
End If
End Function
Note: in a worksheet code module you can use Me to refer to the worksheet, instead of Target.Parent

Worksheet change timestamp multiple columns

So I have this case where a specific range in two separate columns are going to be filled out. In either case there should be a date stamped in column F and time stamp in column G. This version I have works to some extend however when you clear out any cell outside of one you get a type mismatch error
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Handler
If Not Intersect(Target, Range("D8:D31,D44:D67,D80:D103,D116:D139")) And Target.Value <> ""
Then
Application.EnableEvents = False
Target.Offset(0, 2) = Format(Now(), "mm-dd-yyyy")
Target.Offset(0, 3) = Format(Now(), "hh:mm:ss")
Application.EnableEvents = True
Handler:
End If
On Error GoTo Handler2
If Not Intersect(Target, Range("E8:E31,E44:E67,E80:E103,E116:E139")) And Target.Value <> ""
Then
Application.EnableEvents = False
Target.Offset(0, 1) = Format(Now(), "mm-dd-yyyy")
Target.Offset(0, 2) = Format(Now(), "hh:mm:ss")
Application.EnableEvents = True
Handler2:
End If
End Sub
I assuming this breaks the initial if not logic and that is why its erroring out in that manner.
You can simplify this a little by only intersecting on a single range, and also be able to handle multiple cells being updated:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, c As Range
On Error GoTo haveError
Set rng = Application.Intersect(Target, _
Me.Range("D8:E31,D44:E67,D80:E103,D116:E139"))
If Not rng Is Nothing Then 'any cells of interest updated?
Application.EnableEvents = False
For Each c In rng.Cells 'loop over updated cells
If Len(c.Value) > 0 Then 'has value?
With c.EntireRow
.Columns("F").Value = Format(Now(), "mm-dd-yyyy")
.Columns("G").Value = Format(Now(), "hh:mm:ss")
End With
End If
Next c
End If
haveError:
Application.EnableEvents = True
End Sub

VBA Deleting Rows for Changed Cells Debug Error

The following does what I want it to by adding formulas when a value is entered into the Target cell, and then deletes said value when the cell is empty.
However, I keep running into a Debug Error if I were to right-click and delete that row within the Target Range, is there a way to prevent this from happening?
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("C11:C1000")) Is Nothing Then
If Target.Value <> "" Then
Target.Offset(0, -1).Formula = "=VLOOKUP(" & Target.Address & ",UIDs!$F$3:$H$750,3,FALSE)"
Else:
Target.Offset(0, -1).Value = ""
End If
End If
End Sub
Debug Error:
Then it takes me to If Target.Value <> "" Then if I click Debug.
You can confirm that Target is only 1 cell (as it will be a lot more than that when you delete a row):
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("C11:C1000")) Is Nothing Then
If Target.Count > 1 Then Exit Sub
Application.EnableEvents = False
If Target.Value <> "" Then
Target.Offset(0, -1).Formula = "=VLOOKUP(" & Target.Address & ",UIDs!$F$3:$H$750,3,FALSE)"
Else
Target.Offset(0, -1).Value = ""
End If
Application.EnableEvents = True
End If
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

How do I block/clear data for each cell in a column that matches the conditional if statement in VBA?

I am new to VBA programming in excel and would like to know how to do the following (I have searched google and will post what I have tried here with sample code).
Column G, starting at G11 continuing to the end of the sheet, contains 2 values: either "Full Time" or "Part Time".
In column S, starting at S11 continuing until the end of the sheet, our accountant will enter a Dollar value. The Accountant wants the excel cell in Column G to block/clear out any data and have a popup message saying that "You cannot edit this Cell in Column G as the employee is Part Time".
I used this code, but it only works for Row 11. I would like this to work for every row in Column G. Do you have any pointers or tips? Thanks in advance.
I use the 2 events Change and SelectionChange
Private Sub Worksheet_Change(ByVal Target As Range)
If [$G11] = "Part Time" Then
[$S11].Interior.ColorIndex = 34
[$S11].ClearContents
[$S11].Locked = True
Else
[$S11].Interior.ColorIndex = 12
[$S11].Locked = False
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If [$G11] = "Part Time" Then
[$S11].ClearContents
[$S11].Locked = True
Else
[$S11].Locked = False
End If
End Sub
Try this out. I made some assumptions based on what you wrote, so if it doesn't quite fit your data, let me know.
Private Sub Worksheet_Change(ByVal Target As range)
If Not Intersect(Target, .Columns("S:S")) Is Nothing Then 'only do this if column S is changed
Application.EnableEvents = False
If range("G" & Target.Row) = "Part Time" Then
With range("S" & Target.Row)
.Interior.ColorIndex = 34
.ClearContents
.Locked = True
End With
Else
With range("S" & Target.Row)
.Interior.ColorIndex = 12
.Locked = False
End With
End If
Application.EnableEvents = True
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As range)
If Not Intersect(Target, .Columns("S:S")) Is Nothing Then 'only do this if column S is changed
Application.EnableEvents = False
If range("G" & Target.Row) = "Part Time" Then
With range("S" & Target.Row)
.ClearContents
.Locked = True
End With
Else
range("S" & Target.Row).Locked = False
End If
Application.EnableEvents = True
End If
End Sub

Resources