I want to add a new sheet in a Macro Enabled Excel File using VBA.
It doesn't matter the method that I use:
- Sheets.add
- Copying and pasting a sheet to create a new one
The new sheet is created (or copied) but the macro stops immediately, without any message error, and the rest of the code is not executed.
I converted the file to XLSX and when I run the code, the sheet is created and the code execution continues perfectly.
That's why I think that it is related to the Macro Enabled Excel type of file.
UPDATE:
I tested the code in another PC and Excel installation and the new sheet is created and the code goes on.
The only difference between the two computers is the Excel 2016 version:
Standard in one and Professional in the other.
Try this code in your xlsm file:
Dim ws As Worksheet
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
And let me know if this doesn't work.
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.Add or Worksheets.Add line. I found that this was only happening where I was attempting to add a sheet to a workbook that contained VBA code. 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: Application.AutomationSecurity = msoAutomationSecurityLow
来源:https://stackoverflow.com/questions/37858167/error-adding-a-new-sheet-to-a-xlsm-macro-enabled-excel-file