Excel Vba stops excution after deleting sheet - excel

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

Related

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

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

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

VBA Code just stops in the middle execution with out completing code (NOT A HANG)

I have some code that is copying a upwards of 1K files or so from a network drive to a SharePoint site. When it has completed that task, It calls the following sub. When I step through the code it seems to work fine, and it worked fine on some of the smaller lists I uploaded. However when I just let it run it magically stops executing code and behaves as if everything has successfully been executed. I know it hasn't because The workbook I picked to be open is still open and the workbook I am running the code from is blank.
The best I can surmise is the code stops executing right around:
SourceWB.Sheets("Sheet1").Activate
Because the destination sheet is still blank, I am pretty sure the cells.copy is not executing. The only other thing I can think of is it somehow is grabbing the Destination worksheet as the source work sheet, so nothing actually gets copied and I wind up with a blank sheet. I rule that out though as at the end of my main sub a message box is supposed to appear when things are complete and no message box appears.
Can anyone spot an issue or shed some light on what may be happening. Frustrating that it works when stepping through. (as long as there is a break point afterwards)
Sub ImportIndex()
'Copies Sheet1 from a user selected workbook
'into current work book
Dim DestinationWS As Worksheet
Dim DestinationR As Range
Dim SourceWB As Workbook
Dim FilenameWB As String
'clear sheet1 of any previous data/formats etc
Clear_Worksheet ("Sheet1")
'Set the location of where the sheet is to be copied to
Set DestinationWS = ThisWorkbook.Sheets("Sheet1")
Set DestinationR = DestinationWS.Range("A1")
'Open the source workbook through file picker
'****************************************************************
'Error may occur if workbook is already open
'Look into how to deal with this in the future
'****************************************************************
FilenameWB = Application.GetOpenFilename()
Set SourceWB = Workbooks.Open(Filename:=FilenameWB)
'Ensure "sheet1" is the active worksheet
SourceWB.Sheets("Sheet1").Activate
'Copies active wrokesheet to Destination
Cells.Copy DestinationR
'close the source workbook without saving changes
SourceWB.Close savechanges:=False
End Sub
I did look at the following question, but it was related to Word. According to one comment, the most recent build seems to have solved their issue.
Clearworksheet function as requested
Sub Clear_Worksheet(Sheetname As String)
'Deletes all cells in the provide worksheet name
'currently will cause an error if the sheet does not exist
With ThisWorkbook.Sheets(Sheetname)
.Cells.Delete Shift:=xlUp
Range("A1").Activate 'probably do no need this activate
End With
End Sub
I just re ran the code with the elimination of ACTIVATE and also having removed all stepping break points. I also changed the copy line to 'SourceWB.Sheets("Sheet1").Cells.Copy` as suggested. The code still stopped executing after opening the sheet and before copying the sheet to Thisworkbook.
on a side note, I also notice sometimes while stepping through the code and I do a file pick or folder pick, the code seems to terminate unless I have a break point set somewhere slightly after it.
I've commented that not sure why it would stop... having a wild guess it could be because of the very large range you're copying (the whole sheet...).
You should either set the range of what you are copying (cell 1 to last row/column), or in this case, since you are not adding to pre-existent data, could be better off to just copy the sheet.
See if rewriting your code this way would help?
Sub ImportIndex()
'Copies Sheet1 from a user selected workbook
'into current work book
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim SourceWB As Workbook
Dim FilenameWB As String
'Open the source workbook through file picker
On Error Resume Next
FilenameWB = Application.GetOpenFilename()
Set SourceWB = Workbooks.Open(Filename:=FilenameWB)
On Error GoTo 0
If Not SourceWB Is Nothing Then
'ws.Name = "something else" 'rename this if you want to keep "Sheet1" name from the source workbook
SourceWB.Sheets("Sheet1").Copy After:=ws
ws.Delete
'close the source workbook without saving changes
SourceWB.Close savechanges:=False
Else
'Some error handling here... msgbox/debug.print etc
End If
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
PS: Note that there are various ways to handle opening a workbook, but for simplicity reasons, this should work just fine.

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

Workbook will not close with VBA unless opened manually

I have a workbook that I open with VBA, modify said workbook, and then close said workbook. So far what I have is:
Sub OpenandModify()
application.screenupdating = false
workbooks.open Filename:="FilePath\WkbkName.xlsm"
*Modify Workbook
Workbooks("WkbkName.xlsm").close SaveChanges:=True
application.screenupdating = true
End Sub()
If I run the macro with the workbook already open, the macro works correctly and closes the workbook mentioned above. However, if the workbook is not already open, then the file remains open after the modification (Note, the modifications take place so I do not think it is an issue with the Workbook.Open). Any ideas?
Thanks in advance.
After playing around more with my workbook. I seem to have found the issue. In the modify code portion, I have another subroutine that adds a worksheet from a workbook different than WkbkName.xlsm. If the sheet already exists it gets added as Sheet(2) and the workbook will not close. If the worksheet does not exist then the workbook opens and modifies correctly and shuts. I still do not understand why it acts like this so if anyone has any ideas it would be greatly appreciated.
For now, I just plan to add a check for duplicate worksheets and exit the sub if it happens.
Some of the problems you've encountered may be due to the code getting confused with which workbook it's working on.
Use a variable to hold a reference to your workbook and use only that throughout the code:
Sub OpenandModify()
Dim wrkBk As Workbook
Application.ScreenUpdating = False
'Open the workbook and assign it to wrkBk variable.
Set wrkBk = Workbooks.Open(Filename:="FilePath\WkbkName.xlsm")
'Modify Workbook
With wrkBk
.Worksheets("Sheet1").Range("A1") = "Modified!"
End With
wrkBk.Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub

Resources