VBA: Excel Crashes on last Macro (when sheet is deleted) - excel

I wrote several macros for workbook and I have noticed that all the macros run but then at the last action, Excel crashes.
After much troubleshooting, I found the trigger: "Activesheet.move" or "Activesheet.delete." It seems whenever a sheet is deleted from a workbook (or moved to a new workbook), Excel crashes.
Below is the final macro which triggers Excel to crash. The workbook (Template.xlsm) has 3 other sheets so deleting one should not prompt it to close. Essentially, I press the "FinishButton" which is assigned the SaveTemplate() macro. The Macro makes sure there is data in D8 before continuing. It then deletes the "FinishButton" before deleting the activesheet.
Can someone please advise what I am doing wrong or what is causing the crash?
Sub SaveTemplate()
Dim dtToday As String
Dim workdoc As String
dtToday = Format(Date, "mm_dd_yyyy")
workdoc = "Working_Doc_" & dtToday
Workbooks("Template.xlsm").Activate
If Sheets(workdoc).Range("D8").Value = "" Then Exit Sub
Sheets(workdoc).Unprotect Password:="password"
Sheets(workdoc).Shapes.Range(Array("FinishButton")).Select
Selection.Delete
Sheets(workdoc).Protect Password:="password"
Application.DisplayAlerts = False
Sheets(workdoc).Delete
Application.DisplayAlerts = True
Workbooks("Template.xlsm").Save
End Sub
Thank you

Related

Excel VBA update chart not visible

I have an excel file which iterates over different excel files to update them and create a PDF file from them.
The macro iterates over rows and opens the files. This code opens the files:
Private Sub openFile(row As Integer)
Dim filePath As String
Dim wb As Workbook
filePath = Application.ActiveWorkbook.Path + "\" + allRows(row).filename
Set wb = Workbooks.Open(filePath)
Application.Run "RefreshEntireWorksheet"
Application.OnTime Now + (TimeSerial(0, 1, 59)), "'ThisWorkbook.updateCharts """ & row & "'"
Application.OnTime Now + (TimeSerial(0, 2, 59)), "'ThisWorkbook.createEmail'"
End Sub
Now if there are multiple files, only 1 file has the charts properly updated (the file being on the front). It seems like the updateCharts code doesn't work at all:
Sub updateCharts(row As Integer)
Dim SheetName As String
Dim wb As Workbook
SheetName = "Sheet1"
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Set wb = Workbooks(allRows(row).filename)
wb.Activate
wb.Sheets(SheetName).Activate
For Each cht In wb.Sheets(SheetName).ChartObjects
cht.Chart.Refresh
DoEvents
Next cht
End Sub
I checked following links for answers, but none helped:
Can't refresh a chart in Excel VBA (Excel 2016)
Refresh all charts without blinking
excel chart not updating when data changed by vba
Excel 2013 vba refresh chart content after each iteration of For Loop
They all suggest to add an DoEvent, but that doesn't work. So the question is, how can I update charts in a different workbook via VBA?
I have encountered similar issues in the past, and have observed that they seem to increase as the Version of Excel increments; I suspect it is a case of falling afoul of side-effects caused efficiency enhancements elsewhere to speed up the Application in general (reducing unnecessary drawing on the screen, et cetera)
One thing that I have found (sometimes) works is to try and force the Application Window to Refresh/Redraw, by setting the WindowState to itself:
Application.WindowState = Application.WindowState
This is similar to how some people suggest using ActiveWindow.SmallScroll down:=0, ActiveWindow.SmallScroll 0, ActiveWindow.SmallScroll, or ActiveWindow.SmallScroll down:=1: ActiveWindow.SmallScroll up:=1
Combining this with the ScreenUpdating toggle, and the DoEvents, you can create a quick Subroutine like this:
Public Sub RedrawScreen()
Dim ScreenUpdating As Boolean
ScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = True
Application.WindowState = Application.WindowState
DoEvents
Application.ScreenUpdating = ScreenUpdating
End Sub
Try this (it works for me - Excel 2016):
DoEvents must be in your code as others said before
Delete all colours of the cells of the spreadsheet: all the background of the cells must be "no background"; use only automatic colour (black) for the text of all the cells.
Save, close and reopen the file. Now start your macro and look at your chart.
I don't know why it works, but.........it works!
For those more capable than me: do the opposite: if your chart is updating with your macro running, try to colour some text or some cells. The chart will not update anymore. The Microsoft experts should check what is happening.
Hope this helps. Bye, bb.

How to duplicate a worksheet without duplicating its Worksheet Private sub code

I'm trying to duplicate a worksheet with a macro, but when doing so, to private sub is duplicated as well, what I don't want to happen because it interferes afterward with another module macro. I have seen this post Copy a worksheet without copying the code and tried, but it doesn't work properly. Some ideas on how to do that?
Sub Export()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Application.CutCopyMode = False
Sheets("CB").Select
MonthID = Range("N2").Value
YearID = Range("O2").Value
saldoID = Range("O18").Value
ActiveSheet.Unprotect
ActiveSheet.Copy After:=Sheets("CB")
' Get the code/object name of the new sheet...
Dim Code As String
Code = ActiveSheet.CodeName
' Remove all lines from its code module...
With ThisWorkbook.VBProject.VBComponents(Code).CodeModule
.DeleteLines 1, .CountOfLines
End With
The last step (.DeleteLines 1, .CountOfLines) always causes an error: "Can't enter break mode at this moment" - Run time error 1004 Application defined or object defined error.
Why, what is wrong or missing??
Thanks
One simple way:
copy sheet to new workbook
save new workbook as .xlsx
close new workbook
re-open new .xlsx workbook
copy the macro-free worksheet back to original workbook
The VBA code for this is simple; you could also include:
re-close the.xlsx
kill (delete) the .xlsx workbook

Excel BBG formulas not refreshing

I am trying to write a basic script to open another file, refresh the data in that file, save that updated file off as values (not formulae), and then closes the originally opened file containing the formulas without saving. My issue is that the file doesn't actually pull the requested formulae until after the macro has finished and the 'updated' file has saved itself away. In other words the formulae start to refresh, apparently never finish refreshing, and then copy/paste over themselves with the "#N/A Requesting Data..." string, instead of the actual data. I've seen a number of simlar questions around about this, but I haven't seen one which defines why the issue exists in the first place. I have tried runnign the refresh and the saving in different subs, and have tried a number of different methos of waiting for the formulae to finish refreshing, without avail. E.g.:
'ATTEMPT 1
'Application.Calculate
'If Not Application.CalculationState = xlDone Then
' DoEvents
'End If
'ATTEMPT 2
'Do: DoEvents: Loop While Application.CalculationState = xlCalculating
'ATTEMPT 3
'Do Until ActiveSheet.CalculationState = xlDone
' DoEvents
'Loop
Here is the code which runs once the initiating file is openend:
Sub Auto_Open()
Call Refresh
'COPY PASTE VALUES
ActiveSheet.Cells.Copy
'COPY UPDATED SHEET TO NEW BOOK & SAVE AS .XLS
Workbooks.Add
With ActiveSheet
.Cells.PasteSpecial xlValues
.Cells.PasteSpecial xlFormats
End With
Application.CutCopyMode = False
ActiveWorkbook.SaveAs (NewBook & Format(Now(), "DD-MMM-YYYY hh mm AMPM") & ".xls")
End Sub
Here is the sub which actually refreshes the data:
Sub Refresh()
Application.Calculation = xlCalculationManual 'ENSURE IT ONLY PULLS DATA WHEN YOU TELL IT TO
Dim wkbook As Workbook
Dim OpenedBook As String
OpenedBook = "G:\Folder Name\Sub Folder\File Opened in Folder.xlsx" 'FULL PATH OF WORKBOOK TO BE OPENED
NewBook = "G:\Folder Name\Sub Folder\File Saved in Folder\" 'BASE NAME OF THE SAVED WORKBOOK
'OPEN THE DESIRED WORKBOOK
Set wkbook = Workbooks.Open(OpenedBook)
wkbook.Activate
'REFRESH ALL BBG FORMULAE
Application.Run "RefreshAllWorkbooks"
Application.Run "RefreshAllStaticData"
Application.Wait (Now + TimeValue("00:00:10"))
End Sub
The actual formula being refreshed work otherwise, and are straighforward BBG BDH formulae. E.g. =BDP(B3&" curncy", "px_mid") where B3 has a currency pair like "EURUSD". Any thoughts on why the formulae are not pulling, even after the Wait and DoEvents 'fixes'? I have a feleing I am misunderstanding something fundamental about how BBG/VBA works, so please help me understand why this situation exists in the first place. Thanks in advance!

How to detect that an Excel cell has been changed by formula and write data to a CSV file

I have an Excel file that is updated every few seconds by an application. Using the data delivered by the application, several cells in the worksheet (called "TSdata") are calculated using various formulae. If the value of a specific cell (B41) changes, the macro should write the contents of the worksheet to a CSV file.
With the help of one of the guys on superuser.com, I created a version based on Worksheet_Change that worked perfectly if the content of the cell was manually updated. I created a version using Worksheet_Calculate that I expected to work the same way when the cell value was changed by the formula.
This is the code I used:
Private Sub Worksheet_Calculate()
If Worksheets(“TSdata”).Range(“B41”).Value<>prevval Then
Call ExportWorksheetAndSaveAsCSV
End If
prevval = Worksheets(“TSdata”).Range(“B41”).Value
End Sub
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("TSdata") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\TSCSV\TSCSV1.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
FileCopy "C:\TSCSV\TSCSV1.csv", "C:\ChartInfo\Data\TSCSV2.csv"
End Sub
I know from the earlier test using a manual update that the Public Sub works OK (It's copied from another query regarding writing CSV files) but when I launch the macro, it seems to attempt multiple updates (the screen blinks several times) and then crashes Excel. So, obviously something in the Private Sub is incorrect, but I've based it on other responses to similar questions, so I'm at a loss to figure out what's wrong/missing.
Note: the FileCopy at the end of the Public Sub is so that another program can work on the CSV without disrupting the Excel updates.
Thanks in advance for any help.
Copying a worksheet to no location creates a new workbook with a single worksheet that is a copy of the original.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim fn1 As String, fn2 As String
fn1 = "C:\TSCSV\TSCSV1.csv"
fn2 = "C:\ChartInfo\Data\TSCSV2.csv"
'copying a ws to no location creates a new workbook with a single worksheet
ThisWorkbook.Worksheets("TSdata").Copy 'Sheet to export as CSV
Application.DisplayAlerts = False 'Possibly overwrite without asking
With ActiveWorkbook
.SaveAs Filename:=fn1, FileFormat:=xlCSV
.Close SaveChanges:=False
End With
Application.DisplayAlerts = True
On Error Resume Next
If CBool(Len(Dir(fn2))) Then Kill fn2
FileCopy fn1, fn2
On Error GoTo 0
End Sub

Excel Vba stops excution after deleting sheet

I am new to VBA. I have written a code to delete a particular sheet. After execution of that delete sheet macro, excel macro stopped execution. It didnt execute futher..
Here is my code..
Sub CopyAcross()
Dim sheetName As String
sheetName = "Master_Base"
If WorksheetExists(sheetName) Then
DeleteSheet (sheetName)
End If
MsgBox "Debug"
Workbooks("Master_Base.csv").Sheets("Master_Base").Copy Before:=Workbooks("Copy of test.xlsm").Worksheets("Sheet3")
End Sub
Sub DeleteSheet(strSheetName As String)
' deletes a sheet named strSheetName in the active workbook
Application.DisplayAlerts = False
Sheets(strSheetName).Delete
Application.DisplayAlerts = True
End Sub
Can any one help on this,
Thanks in advance.
I was experiencing the same issue, on a Windows 7 computer with Excel version 16.0.10730.20264 32-bit, the code ran fine without issue. However, on a Windows 10 computer with the same Excel install version, the macro would immediately stop execution following the Sheets.Delete line.
I found that this was only happening where I was attempting to manipulate a workbook that contained VBA code, that I had opened during the macro.
The issue is caused by the macro security settings on the computer. If you set Automation Security to Low before opening the workbook, you should no longer get the error:
Use the code:
Application.AutomationSecurity = msoAutomationSecurityLow
Since you are working with multiple workbooks, use objects. Else your code MAY work with the wrong workbook/worksheet
Try this (UNTESTED)
Sub CopyAcross()
Dim wbI As Workbook, wbO As Workbook
'~~> The workbook from where the code is running
Set wbO = ThisWorkbook
'~~> Here you open the csv
Set wbI = Workbooks.Open("E:\OPM\OPM Sheet\Master_Base.csv")
'~~> This will delete the sheet if it exists
'~~> no need to check if it exists
On Error Resume Next
Application.DisplayAlerts = False
wbO.Sheets("Master_Base").Delete
Application.DisplayAlerts = True
On Error GoTo 0
'~~> The csv will always have 1 sheet
'~~> so no need providing a name
wbI.Sheets(1).Copy Before:=wbO.Worksheets("Sheet3")
End Sub

Resources