I want Excel to calculate the sheet, every time the user enters a value (source1 source2):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Worksheet("Calc").Range("R1:R100")
MsgBox "Check!"
Application.EnableEvents = False
If Not Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
' Display a message when one of the designated cells has been changed.
MsgBox "Cell " & Target.Address & " has changed."
'Calculate
Sheets("Calc").Calculate
End If
Application.EnableEvents = True
End Sub
The sheet does not get recalculated after entry of value. Even, the message box "Check!" never appears. - Why is that?
(For info: I can only guess that it has something to do with my setting the calculation to "manual":
I have a sheet in Workbook "B.xlsm" with circular references, hence I run a script from Workbook "A.xlsm", from where I open Workbook "B.xlsm":
Application.Calculation = xlManual
[...]
Set wb = Workbooks.Open(strPath)
Is there a way to get this method "Change" to work with manual calculation?)
I think Tim nailed it.
At some point in testing the code, the code stopped; Either from and Run-time Error or manually stepping through line-by-line. In either case, you probably changed something which forced it to reset and it never had a chance to run the most important line...Application.EnableEvents = True.
Disabling Events is a persistent state.
It's very wise to make sure that you have error handling working to restore it, if other users are going to be using your code. Unfortunately, you'll still break it while testing.
I use the following routine (at the top of the main module) to fix it, when this happens:
Public Sub FixIt()
Application.EnableEvents = True
If Not ActiveWindow Is Nothing Then Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
In fact, I usually call this routine as the first line of any button I have on the Ribbon/Sheet, just to make sure that everything is working like it should be.
In your case, you could omit the Application.Calculation line, or set it equal to xlManual
Related
I have some VBA code as follows:
Sub copyData(fromRange as Range, toRange as Range)
Application.ScreenUpdating = False
<copy paste code here>
Application.ScreenUpdating = True
End Sub
Even though I am setting Application.ScreenUpdating to False, it remains at True. I have verified this using F8 and hovering over Application.ScreenUpdating (it shows True).
My copy paste code works. It switches worksheets but since ScreenUpdating remains at True, I can see the screen flicker.
Is there a way to set Application.ScreenUpdating to False?
P.S. I saw a similar question in this forum but there was no concrete resolution to it.
Any help will be greatly appreciated!
I've had the same issue for quite a while, and I figured out something: Application.screenUpdating only stays FALSE for how ever long a macro runs. When any macro running stops, it turns True. You can try this:
Sub testApplicationScreenUpdating()
Application.ScreenUpdating = False
Debug.Print "Application screen updating is:" & Application.ScreenUpdating
Application.ScreenUpdating = True
End Sub
if you just run this, it will return in the Immediate window: "Application screen updating is:False"
if you run it step by step, and hover over Applicaiton.ScreenUpdating with your mouse, it will show as "True", even if the Immediate window will show "False".
if you comment out the [Application.ScreenUpdating = True] at the end, and then run [Debug.Print "Application screen updating is:" & Application.ScreenUpdating] separately, it will return true, even if it was not switched to true.
Try this code and see the values for each in the Immediate Window Ctrl+G:
Sub copyData()
Dim r As Boolean
r = Application.ScreenUpdating = False
Debug.Print "'Application.ScreenUpdating' is set to " & r
r = Application.ScreenUpdating = True
Debug.Print "'Application.ScreenUpdating' is set to " & r
End Sub
I use Excel as part of Microsoft 365. I too fought with the screen flickering problem. Although my macro worked, the flickering was very annoying. I tried several approaches and stumbled upon this:
Minimize the second workbook before initiating the macro from the first workbook. For my situation, the screen no longer flickered. I also tried the following code to minimize the second workbook from within VBA. If the second workbook was already minimized, there was no effect. If the second workbook was not minimized, the screen flickered only once - to enable me to minimize the second workbook. Subsequent switching back and forth between workbooks did not introduce any screen flickering.
‘
Filename = "SecondWorkbookName.xlsx"
Windows(Filename).Activate
Application.WindowState = xlMinimized ' Minimize workbook to prevent flickering.
Application.ScreenUpdating = False
I have a spreadsheet where users paste numbers, due to the length of these numbers (and the fact that we don't need to spreadsheet to carry out any computations with them) we want them to be formatted as text, otherwise they appear in scientific format i.e. 1.12345E+13 instead of 12345678912345
It is not possible to adjust/modify the data source the numbers are being copied from.
I'm using Private Sub Workbook_SheetChange do detect if a cell in the relevant range has been changed, and I then format the range to text with
ThisWorkbook.Sheets("Sheet1").Columns("B").NumberFormat = "#"
Unfortunately on Excel 2007 whether you do this manually in Excel or via a marco, the number still appears as 1.12345E+13 unless you click into the cell and press enter.
I can get round this by applying:
With rng
.Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
End With
but when I do this I end up with an infinite loop, as the Private Sub Workbook_SheetChange detects the cell has been changed and goes round the loop again.
If I could somehow work out whether the cell has been changed manually by the user or by the macro, this would be easily fixed. The macro is in ThisWorkbook. I've tried using Application.Activesheet instead of ThisWorkbook.Sheets but it didn't make any difference.
If alternatively there's an easier/better way to fix numbers being displayed as 1.12345E+13 even after I've re-formatted the cell I'd love to know about it.
Thank you.
but when I do this I end up with an infinite loop, as the Private Sub Workbook_SheetChange detects the cell has been changed and goes round the loop again.
That's because you need to disable application events from automatically firing.
Private Sub Workbook_SheetChange(ByVal Sh As Worksheet, ByVal Target As Range)
Application.EnableEvents = False '// Stop events automatically firing
With rng
.Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
End With
Application.EnableEvents = True '// Re-enable events for next time
End Sub
Because you've disabled the events, it can't trigger itself again when you change the value of the cell. Once the code has completed you can re-enable the events to ensure that it fires the next time it is required.
For what it's worth, don't beat yourself up about it - this is an extremely common pitfall when people start working with event procedures in excel-vba.
Here's a full example, including handling Target ranges of >1 cell:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim c As Range
Application.EnableEvents = False
On Error GoTo haveError
For Each c In Application.Intersect(Target, Sh.UsedRange).Cells
With c
If IsNumeric(.Value) Then
.NumberFormat = "#"
.Value = CStr(.Value)
End If
End With
Next c
haveError:
'Make sure to re-enable events!
Application.EnableEvents = True
End Sub
I have a series of data, running from cells C169:N174, sourcing a line chart. Cell data is either a number, or empty (Excel empty) - the formula returns either the number or blank text ("").
When the action is triggered, via data validation, I need the formulas in the right-most cells (N169:N174) copied left through C169:C174). To accomplish this, I have this code:
Range("N169:N174").AutoFill Destination:=Range("C169:N174")
Range("C169:N174").Select
After the formulas are copied, I need any cell containing text (""), to be cleared. To accomplish this, I have this code:
Range("C169:M174").SpecialCells(xlCellTypeFormulas, 2).Select
Selection.ClearContents
This code runs for two sets of data. Same code, different cells. Ranges are C169:N174 and C145:N150. I have the code written for range1 (C145:N15) first - formulas copy then cells w/ ("") deleted. Then same action for range2 (C169:N174). Full code:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
If Target.Address = "$B$2" Then
'mcroCopyTrendedRentFormulas
Range("N145:N150").AutoFill Destination:=Range("C145:N150"), Type:=xlFillDefault
Range("C145:N150").Select
'mcroClearTrendedRentEmptyCells
Range("C145:N150").SpecialCells(xlCellTypeFormulas, 2).Select
Selection.ClearContents
'mcroCopyAskingRentFormulas
Range("N169:N174").AutoFill Destination:=Range("C169:M174")
Range("C169:N174").Select
'mcroClearAskingRentEmptyCells
Range("C169:M174").SpecialCells(xlCellTypeFormulas, 2).Select
Selection.ClearContents
Range("A1").Select
End If
End Sub
Once the code is triggered, if I click anywhere on the sheet before it has finished running, which I just timed and it took 45 seconds, I get an error saying either:
"1004 Error: No cells were found"
or
"1004 Error: AutoFill method of Range class failed".
If I let the code run the entire 45 seconds, it works. If I click anywhere in the sheet and get either error, stop the debugger and try to run it again, I get one of the two errors.
So maybe speeding up execution is the issue?
I don't know - open to anything here.
I slightly edited the code, mainly removing superfluous .Select lines (well, commented them out) and combined .Select and .ClearContents. This should run a little faster. Note the use of ScreenUpdating and Calculation.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$2" Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
'mcroCopyTrendedRentFormulas
Range("N145:N150").AutoFill Destination:=Range("C145:N150"), Type:=xlFillDefault
'Range("C145:N150").Select
'mcroClearTrendedRentEmptyCells
Range("C145:N150").SpecialCells(xlCellTypeFormulas).ClearContents
'mcroCopyAskingRentFormulas
Range("N169:N174").AutoFill Destination:=Range("C169:M174")
'Range("C169:N174").Select
'mcroClearAskingRentEmptyCells
Range("C169:M174").SpecialCells(xlCellTypeFormulas).ClearContents
Range("A1").Select
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
I also removed the 2 from your SpecialCells() as I don't believe that's required, and was throwing an error for me as well until I removed it.
While this is running, let it run without clicking. Really while any Macro is running in Excel, it's best to just let it sit and run.
I have a spreadsheet that is going to be used in a survey.
How can I make the cells only to return "x" regardless of what the survey taker type in.
For instance, if I write a "w" in the cell, it should turn into an "x".
I have come to a point where I think there is an option when I protect the workbook or sheet. Because I can tell from another spreadsheet (which has this function) that it only works if the workbook is protected.
I tried to google it, but it seems as if I don't know the right keywords to find the answer.
Also, I have found a set of Vba code that I fiddle with, but I'm not sure this is correct. I don't want to attach the code as I don't want to confuse any response here.
Thank you for any help provided.
Put this code in the worksheet module and test it out, when you change a cell in column A (1) it will activate,
Where is the worksheet Module?
Copy and paste the code ,
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Intersect(Target, Range("A1,B1,C1,A4,B4,C4")) Is Nothing Then Exit Sub
Application.EnableEvents = 0
If Target <> "" Then Target = "X"
Application.EnableEvents = 1
End Sub
This should work for you (just change the range to the one you need) :
Option Explicit
Sub worksheet_Change(ByVal Target As Range)
On Error GoTo errorbutler 'error handler - important to have this in case your macro does a booboo
Application.Calculation = xlCalculationManual 'turn off automatic calculation to speed up the macro
Application.EnableEvents = False 'turn off events in order to prevent an endless loop
Dim LR, cell As Range 'Declare your variables
Set LR = Range("A1:b3") ' Select range of cells this macro would apply to
For Each cell In Target 'Loops through the cells that user have changed
If Union(cell, LR).Address = LR.Address Then 'Checks if the changed cell is part of your range
cell.Value="x" 'changes the value of that cell to x
End if
Next cell
Errorexit: 'part of error handling procedure
Application.EnableEvents = True 'Turn autocalc back on
Application.Calculation = xlCalculationAutomatic 'turn events back on
Exit Sub
Errorbutler: 'error handling procedure
Debug.Print Err.Number & vbNewLine & Err.Description
Resume Errorexit
End Sub
Oh yes, and this code should be put into the worksheet module - the same way as Dave has shown you
I am trying to delete a worksheet when the user click's on an image (button) in Excel. However this makes excel crash and restart, forgetting any unsaved progress.
This is my sub:
Sub DeletePlan()
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim SheetNamesToCopy As String
SheetNamesToCopy = ActiveSheet.Name
' Check what addon sheets exists for the media, then add existing ones to string
If CheckSheet("periodeplan", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - periodeplan").Delete
End If
If CheckSheet("ukesplan", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - ukesplan").Delete
End If
If CheckSheet("Input", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - Input").Delete
End If
SheetS("Totalplan").Select
ThisWorkbook.SheetS(SheetNamesToCopy).Delete
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
The application crashes most of the time. But not always... Any ideas what might be wrong?
(I have tested and confirmed that the delete function causes the crash, but its not always the same sheet).
Edit: This function is not deleting the last sheet in the workbook. There are 20 more sheets. Also i use Application.Calculation = xlCalculationAutomatic, because there are allot of formulas, and i do not want excel to calculate changes before all is connected sheets are deleted.
Any hint or answer is appreciated :)
The error occurs when the button that initiates the macro is located on one of the sheets that are to be deleted.
So the answer is: Do not create a button (or image linked to a macro) that deletes the sheet it is on.
If anybody can add to this answer with a reason for this error, please do so ;)
I just ran into this problem myself! I'm going to defer to more experienced designers on a way to refine this technique, but as a general concept, I do have a working solution:
If you allow the macro to run it's course and then delete the sheet, it doesn't crash. Something like this:
Sub Delete_This_Sheet()
Application.OnTime Now + TimeValue("00:00:02"), "Watergate"
Sheets("Sheet with a death sentence").Visible = False
End Sub
Sub Watergate() 'To make things go away
Application.DisplayAlerts = False
Sheets("Sheet with a death sentence").Delete
Application.DisplayAlerts = True
End Sub
Resurrecting this thread because I had the same issue and want to share the solution.
I had a very simple sub to delete worksheets:
Sub deletetraindoc()
Dim ws As Worksheet
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Sheets
'This if statement looks for any worksheet that contains the term "Form"
'Any worksheet that contains that string will be deleted
If InStr(ws.Name, "Form") > 0 Then
Application.DisplayAlerts = False 'Deactivates the standard deletion confirmation
ws.Activate
ws.Delete 'Deletes the worksheet
Application.DisplayAlerts = True 'Reactivates display alerts
End If
Next
Application.ScreenUpdating = True
End Sub
This inconsistently caused crashing until I added the line "ws.Activate" to activate each worksheet before deleting, which seems to have resolved the issue. I've run into this problem in many other situations performing actions on worksheets, but it usually would result in an object error instead of a complete crash.
I found that in Office 2013, you cannot place a button that overlaps a cell that that macro changes. Interesting enough, it doesn't occur if the change is numeric in nature, but if it is alphanumeric, it blows up excel when you attempt to delete that tab. Turns out, it blows it up when attempting to delete the tab manually (by mouse click) or by the macro attempting to do it. THUS, my lesson learned from this thread and applying it to my specific situation is to never place a development button over the cell it changes (in my case, it was simply a cell that gives the status of what that macro was doing). Excel 2013 does not like that situation while Excel 2010 simply didn't care.
I do believe you nare right and the only way around this is to ensure this macro is on the total plan sheet. Also you're doing a few unnecessary steps and the select a sheet should be to activate and select a cell.
Sub DeletePlan()
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim SheetNamesToCopy As String
SheetNamesToCopy = ActiveSheet.Name
'dont delete total plan
If sheetnames = "Totalplan" then exit sub
SheetS("Totalplan").Activate
Activesheet.Cells(1,1).select
'Turn off errors if sheet doesn't exist
On error resume next
ThisWorkbook.SheetS(SheetNamesToCopy & " - periodeplan").Delete
ThisWorkbook.SheetS(SheetNamesToCopy & " - ukesplan").Delete
ThisWorkbook.SheetS(SheetNamesToCopy & " - Input").Delete
ThisWorkbook.SheetS(SheetNamesToCopy).Delete
On error goto 0
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
You can delete the active sheet from a button (or image) on the active sheet. You just have to work around it.
ActiveSheet.Move before:=Worksheets(1)
Worksheets(2).Activate
Worksheets(1).Delete
I had a similar, but not identical problem. I had a macro that deleted all the chart sheets with the following command, but although it operated correctly, Excel 2013 was doomed to fail as soon as I tried to save the file, and would "recover" by reverting to the previously saved situation, throwing away any subsequent work:
Oh, and it worked fine until I moved from, I think it was, Excel 2010 to 2013, changing to Windows 10 at the same time.
The command of doom was:
ThisWorkbook.Charts.Delete
Thanks to some inspiration from the answers above, I first inserted a save before the deletion action and then changed the delete as follows (it turned out the saves were not after all needed but I like to have them there, even if I comment them out):
Dim graphSheet As Chart
ActiveWorkbook.Save
For Each graphSheet in this Workbook.Charts
graphSheet.Delete
ActiveWorkbook.Save
Next graphSheet
I should also mention that there is a preceeding Application.DisplayAlerts = False before the for loop and of course the Application.DisplayAlerts = True after the Next... statement to cut out the unwanted
are you sure you want to do this type question?
Again, thanks to your contributors for the inspiration.
I wanted a button that would delete a sheet, as the workbook was protected and could 'export' results but couldn't delete unwanted results.
My simple workaround was to have the macro hide the sheet, but then to delete the last hidden sheet, so the files dont become huge with dozens of hidden sheets.
I created a range in a hidden sheet called "DeleteSheet", to store the name of the hidden sheet.
Sub Delete_Sheet()
ActiveWorkbook.Unprotect Password:="Patrick2017"
ActiveSheet.Unprotect Password:="Patrick2017"
On Error Resume Next
' (In event there is no hidden sheet or the sheet is already deleted, resume next)
'The below finds the name of the previously hidden sheet to delete, and stores it.
Dim DeleteSheet As String
DeleteSheet = Range("DeleteSheet")
'The below is to avoid the main sheet being deleted
If ActiveSheet.Name = "POAL Calculator" Then
Exit Sub
End If
' The below stores the current sheets name before hiding, for deleting next time the
' macro is run
Range("DeleteSheet") = ActiveSheet.Name
ActiveWindow.SelectedSheets.Visible = False
' The below deletes the sheet previously hidden
Application.DisplayAlerts = False
Sheets(DeleteSheet).Delete
ActiveWorkbook.Protect Password:="Patrick2017"
Application.DisplayAlerts = True
End Sub
How about moving the button code to a module?
I have had an issue with that in Excel 2016 whereby Option explicit didn't work if the code was in a module, but if the code is in a module, then you 'should' be able to delete the sheet where the button was.