Excel/Excel VBA cut and copy resets cell name - excel

The situation is simple, if I name cell A1 to be MY_CELL and then CUT AND PASTE from cell A2 to cell MY_CELL, then MY_CELL will lose that name and be named A1 again.
However, this does not happen when I COPY AND PASTE from A2 to MY_CELL.
How can I prevent Excel from resetting cell names on CUT AND PASTE?

Logic: Trap the changes to Cell A1 using the Worksheet_Change event and recreate the name if it is lost.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim DoesRngNameExists As Boolean
Dim sName As String
On Error GoTo Whoa
Application.EnableEvents = False
'~~> You named range
sName = "MY_CELL"
If Not Intersect(Target, Range("A1")) Is Nothing Then
'~~> Check if the Range exists
On Error Resume Next
DoesRngNameExists = Len(Names(sName).Name) <> 0
On Error GoTo 0
'~~> If not then recreate it
If DoesRngNameExists = False Then _
ThisWorkbook.Names.Add Name:=sName, RefersToR1C1:="=Sheet1!R1C1"
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
Note: The codes in the Sheet code area of the relevant sheet. See screenshot below.

Related

Problem with Copy and PasteSpecial (changing sheet name )

The below code copy rows from sheet "Opened" (based on condition ) and paste on another sheet "Closed" in the same workbook and there is another event code on sheet "Closed" to prevent change name of that sheet.
Problems:(1) If I run copy code while sheet "Opened" is activated ,I got Run-time error 1004 That name is already taken. this error related to sheet "closed". no such error if I run code while sheet "closed is" activated.
Sub Copy_PasteSpecial()
Dim StatusColumn As Range
Dim DestRng As Range
Dim Cell As Object
Set StatusColumn = Sheets("Opened").Range("H3", Sheets("Opened").Cells(Rows.count, "H").End(xlUp))
For Each Cell In StatusColumn
If Cell.value = "Close" Then
Set DestRng = Sheets("Closed").Range("A" & Rows.count).End(xlUp).Offset(1, 0)
Cell.EntireRow.Copy
DestRng.PasteSpecial xlPasteValuesAndNumberFormats
DestRng.PasteSpecial xlPasteFormats
End If
Next Cell
End Sub
And this code for Prevent Changing Sheet Name:
Private Sub worksheet_SelectionChange(ByVal Target As Excel.Range)
If ActiveSheet.name <> "Closed" Then
ActiveSheet.name = "Closed"
End If
End Sub
This link for the real workbook: https://easyupload.io/7ftxik
The issue is that ActiveSheet in
Private Sub worksheet_SelectionChange(ByVal Target As Excel.Range)
If ActiveSheet.name <> "Closed" Then
ActiveSheet.name = "Closed"
End If
End Sub
is not the sheet the SelectionChange event is in. That would be Target.Parent
Private Sub worksheet_SelectionChange(ByVal Target As Excel.Range)
If Target.Parent.Name <> "Closed" Then
Target.Parent.Name = "Closed"
End If
End Sub

Restrict Worksheet_Change to a specified range of cells

I want to record a list of live data in a separate sheet.
Found this code online which works.
How to do I change the range from one cell A1 to a Range A1:D30?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim dest As Range
Application.EnableAnimations = False
On Error GoTo line1
If Target.Address <> "$A$1" Then GoTo line1
Set dest = Worksheets("sheet2").Cells(Rows.Count, "a").End(xlUp).Offset(1, 0)
'MsgBox dest.Address
Target.Copy dest
line1:
Application.EnableEvents = True
End Sub
This can be done without a custom function. VBA already contains all you need.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:D30")) Is Nothing Then
' run some code
End If
End Sub

Dynamic Loop Range, VBA

I'm creating macro Excel that will check if there is empty cells in specific range before closing the Workbook. I have an issue that the range is dynamic , and I have cell that contain the range that I want to check each time, how can I use cell value inside VBA as range.
and this is the VBA
Private Sub Workbook_BeforeClose(Cancel As Boolean)
For Each cell In Range("A2:E2")
If cell.Value = "" Then
MsgBox "Please, fill empty cells", vbInformation, "Warning"
cell.Select
Cancel = True
Exit Sub
End If
Next
End Sub
Private Sub Workbook_Open()
End Sub
thank you
Try this code
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim e, cell As Range
e = Range("O11").Value
If IsNumeric(Evaluate("SUM(" & e & ")")) And Not IsNumeric(e) Then
For Each cell In Range(e)
If cell.Value = "" Then
MsgBox "Please, Fill Empty Cells", vbInformation, "Warning"
cell.Select
Cancel = True: Exit Sub
End If
Next cell
End If
End Sub

Excel Worksheet_Change not detecting changes

Unfortunately Worksheet_change is not working for me. I am using a Sheet where the first column is NOW() function. If I click anywhere in the excel the time on this cell changes, but the Worksheet_Change just don't detect it.
A2 is using =NOW()
Anyone knows how to fix this issue? I have tried several different ways and no one works.
'Option Explicit
'Option Base 1
Dim xVal As Double
'Update by Extendoffice 2018/8/22
'Private Sub Worksheet_Calculate(ByVal Target As Range)
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Address = Range("$A$2").Address Then
'Rows(3).Insert Shift:=xlDown
'Range("$A$3").Value = Now
'Range("$B$3").Value = xVal
'Range("$C$3").Value = Range("$C$2").Value
'Else
If xVal <> Range("$B$2").Value Then
Debug.Print xVal & " <- xVal IF"
Debug.Print Range("B2").Text & "<- Text IF"
Rows(3).Insert Shift:=xlDown
Range("$A$3").Value = Now
Range("$B$3").Value = xVal
Range("$C$3").Value = Range("$C$2").Value
End If
End If
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
xVal = Range("$B$2").Value
End Sub
A Worksheet_Calculate Event Study
Google Drive
Cell A2 in worksheet Sheet1 contains the formula =B2.
Sheet1
Option Explicit
Private Sub Worksheet_Calculate()
WsCalc
End Sub
' Only to trigger the calculate event when different cell is selected.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ThisWorkbook.Worksheets("Sheet1").Range("B2") = Int(Rnd() * 2 + 1)
End Sub
ThisWorkbook
Option Explicit
Private Sub Workbook_Open()
WsCalc
End Sub
Module1
Option Explicit
Public lngSource As Long ' Current Source Value
Sub WsCalc()
Dim rngSource As Range ' Source Cell Range
' Create a reference to Source Cell Range (rngSource).
Set rngSource = ThisWorkbook.Worksheets("Sheet1").Range("A2")
' When the workbook opens, Current Source Valuec (lngSource) is equal to "".
' Therefore:
If lngSource = 0 Then
' Initialize Current Source Value (lngSource) i.e. write value
' of Source Cell Range (rngSource) to Current Source Value (lngSource).
lngSource = rngSource.Value
MsgBox "Monitoring started (lngSource=" & lngSource & ")."
Exit Sub
End If
' If you need disabling events, this is how you implement it. Not needed
' in this code.
' Application.EnableEvents = False
On Error GoTo ProgramError
' Check value of Source Cell Range (rngSource)
' against Current Source Value (lngSource).
If rngSource.Value <> lngSource Then
' The value has changed.
MsgBox "The value has changed from '" & lngSource & "' to '" _
& rngSource.Value & "'."
lngSource = rngSource.Value
Else
' The value hasn't changed (usually no code).
MsgBox "Value NOT changed, still '" & lngSource & "'"
End If
SafeExit:
' MsgBox "Enabling events before exiting."
' Application.EnableEvents = True
Exit Sub
ProgramError:
' Improve this error handling.
MsgBox "An unexpected error occurred."
On Error GoTo 0
GoTo SafeExit
End Sub

Dynamic sheet names based on dependent cells

Apologies if this is simple, but I am new to VBA. I am attempting to set up the my Excel sheet so that when certain cells in the first sheet are changed (eg A1, A2, A3, A4) the names of four other sheets will change to match them. I have found the following formula which works if I change the specific cell on that sheet;
`
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Set Target = Range("A1")
If Target = "" Then Exit Sub
On Error GoTo Badname
ActiveSheet.Name = Left(Target, 31)
Exit Sub
Badname:
MsgBox "Please revise the entry in A1." & Chr(13) _
& "It appears to contain one or more " & Chr(13) _
& "illegal characters." & Chr(13)
Range("A1").Activate
End Sub
` Unfortunately it will not work if I change A1 to be dependent on one of the four cells on the main sheet specified previously, as it only looks for changes in the sheet it is saved in.
Is there a way to use VBA to look at a cell in one sheet and then change the sheet name of another sheet to match?
Thanks
Like I mentioned in the comments, it's not that simple to rename the sheet. You have to check for so many things.
My Assumptions
You have 5 Sheets in a workbook; Sheet1, Sheet2, Sheet3, Sheet4 and Sheet5
When you change cells in Sheet5, depending on the cell which changes, Sheets1-4's names are changed
I am assuming that when A1 changes, Sheet1 is renamed. When A2 changes, Sheet2 is renamed and so on...
Logic
Use Worksheet_Change event to trap changes to cell A1, A2, A3 or A4
Use Sheet CodeName to change the name
Check if the sheet name is valid. A sheet name cannot contain any of these Characters \ / * ? [ ]
Check if you already have a sheet with the name you want to use for renaming
If everything is hunky dory then go ahead and replace
Code
See this example. This code goes in the Sheet5 code area.
Dim sMsg As String
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wsName As String
On Error GoTo Whoa
sMsg = "Success"
Application.EnableEvents = False
If Not Target.Cells.CountLarge > 1 Then
If Not Intersect(Target, Range("A1")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet1], wsName
ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet2], wsName
ElseIf Not Intersect(Target, Range("A3")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet3], wsName
ElseIf Not Intersect(Target, Range("A4")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet4], wsName
End If
End If
MsgBox sMsg
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
'~~> Procedure actually renames the sheet
Sub RenameSheet(ws As Worksheet, sName As String)
If IsNameValid(sName) Then
If sheetExists(sName) = False Then
ws.Name = sName
Else
sMsg = "Sheet Name already exists. Please check the data"
End If
Else
sMsg = "Invalid sheet name"
End If
End Sub
'~~> Check if sheet name is valid
Function IsNameValid(sWsn As String) As Boolean
IsNameValid = True
'~~> A sheet name cannot contain any of these Characters \ / * ? [ ]
For i = 1 To Len(sWsn)
Select Case Mid(sWsn, i, 1)
Case "\", "/", "*", "?", "[", "]"
IsNameValid = False
Exit For
End Select
Next
End Function
'~~> Check if the sheet exists
Function sheetExists(sWsn As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets(sWsn)
On Error GoTo 0
If Not ws Is Nothing Then sheetExists = True
End Function
Screenshot

Resources