How to save file without the Excel VBA code in it? - excel

Below is my code for saving the file without the VBA codes.
It saves together with the VBA codes.
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C",
FileFormat:=xlExcel8
Application.DisplayAlerts = True
Next x
End Sub

Save your project as xlsx instead of xlsm then the Code shouln'd be saved

you could first copy sheets in a new workbook and then save it
Sheets.Copy
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.CutCopyMode = False
With ActiveWorkbook
Application.DisplayAlerts = False
.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C.xlsx"
Application.DisplayAlerts = True
.Close True
End With

from
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C", FileFormat:=xlExcel8
to this:
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C" & ".xlsx", FileFormat:=xlOpenXMLWorkbook

SaveAs Confusion
I'm confused, too. As it happens, when you save your macro enabled workbook (.xlsm) as macro not-enabled workbook (.xlsx), the workbook stays open still having the code in it. But the good thing is that it is saved without code. You can now save it, 'manually' SaveAs it, it will still be without code (macros) the next time you open it.
The code should demonstrate the following:
It is good practice to start with Option Explicit which will help
you by alerting you when something is wrong.
It is good practice to use constants at the beginning of the code,
especially for such long file paths, so when you have to change them
you can easily find them.
When you disable an event, there is a possibility you won't be able
to enable it again if you're not careful. If an error occurs, you should redirect
the code to enable those events again.
If you want to close the workbook, then use the line ThisWorkbook.Close
Option Explicit
Sub SaveMacroDisabled()
Const strPath = "I:\Excel\MyDocuments\Test\Test4\"
Const strXLSX = "BookMacroDisabled"
On Error GoTo ProgramError
Application.DisplayAlerts = False
ThisWorkbook.SaveAs strXLSX, _
FileFormat:=xlWorkbookDefault
SafeExit:
Application.DisplayAlerts = True
' ThisWorkbook.Close
Exit Sub
ProgramError:
MsgBox "An unexpected error occurred"
On Error GoTo 0
GoTo SafeExit
End Sub

Related

Button (form control) runs Macro incorrectly

I've created a macro to export several tabs of a spreadsheet to csv files, then reopen the original document. Normally the macro runs correctly, however when run through a button it fails to find other sheets in the workbook.
The document contains 5 tabs: 1 for the button, and 4 for the data (hardcoded below). When I run the macro, it exports the 4 sheets correctly but when I press the button, it exports the first sheet 4 times (the one containing the button, not listed in the macro). All I can think is that the button is failing to pass the active workbook to the macro, and therefore it cannot "see" the Worksheets object...is there something I can do to fix this?
Note that all lines other than the SaveAs commands are (theoretically) unrelated. I have tried replacing "Worksheets" with "ActiveWorkbook.Worksheets" and gotten the same result.
Sub SaveAsCSVs()
Dim fullname As String
fullname = ThisWorkbook.fullname
Application.DisplayAlerts = False
Worksheets("Ships").SaveAs Filename:=ThisWorkbook.path & "\ships", FileFormat:=xlCSV
Worksheets("Weapons").SaveAs Filename:=ThisWorkbook.path & "\weapons", FileFormat:=xlCSV
Worksheets("Specials").SaveAs Filename:=ThisWorkbook.path & "\specials", FileFormat:=xlCSV
Worksheets("Modifiers").SaveAs Filename:=ThisWorkbook.path & "\modifiers", FileFormat:=xlCSV
Application.Workbooks.Open (fullname)
Application.DisplayAlerts = True
Workbooks("modifiers.csv").Close
End Sub
Strange, behavior, indeed...
Being a single sheet to be saved, please use the next adapted code. It should work in both cases:
Sub SaveAsCSVs()
Dim fullname As String
fullname = ThisWorkbook.fullname
Application.DisplayAlerts = False
Worksheets("Ships").Copy 'it creates a new workbook containing only the copied sheet...
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\ships", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Weapons").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\weapons", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Specials").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\specials", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Modifiers").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\modifiers", FileFormat:=xlCSV
ActiveWorkbook.Close False
'Application.Workbooks.Open (fullname) 'no need to open, it remained opened...
Application.DisplayAlerts = True
End Sub

Issue with VBA converting .XLSX file to bulk .CSV

I have an excel file received on a monthly basis that includes multiple sheets. Each sheet needs to be split into .CSV files before it can be uploaded into our system for reading, and given that a single workbook might include upwards of 10 to 15 pages, it's a chore to do it by hand.
Presently, I'm using this VBA script to achieve the job:
Sub Splitbook()
'Updateby20140612
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".csv"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
It "works". The problem? When you try to open the generated csv windows complains about an extension mismatch and warns about corruption. If you click through the dialogue it opens anyway, but the target system can't do that. So I'm left with figuring out what's missing or going back to parsing by hand. Any help?
I've created a version which combines your code with the relevant parts of the other answer. The open workbook will take the names of each of the worksheets in turn. It will therefore be important to save your workbook BEFORE running this code. The version which is open at the end will have all the tabs, but they aren't in the saved CSV file of the same name.
If you want to save again at the end back to the original name and format, I think some of the other answers can help with that too.
I've removed the Worksheet Copy command and commented out the Application.ActiveWorkbook.Close False line as I wasn't sure what they were doing.
Sub Splitbook()
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.SaveAs Filename:=xPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV
'Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

VBA - SaveCopyAs hidden

Everytime I save my workbook I need to save the same workbook, but Hidden.
Now I have this code
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
ThisWorkbook.Saved = True
On Error Resume Next
If Not (Left(ThisWorkbook.Name, 2) = "Z_") Then
Application.DisplayAlerts = False
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name
SetAttr ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name, vbHidden
Application.DisplayAlerts = True
End If
SetAttr ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name, vbHidden
End Sub
However it works only every second time. First time I save WB, it creates the file and make it hidden, but when I save it second time it deletes the hidden file.
When I use SaveAs with overwrite property it saves file and activate it, but I dont want that.
Why is that? How to solve this please?
When you have a problem like this, the first this to do is to comment out On Error Resume Next and Application.DisplayAlerts = False. That will give you far more information on what's going on.
In your case, you had a problem with preexisting files. Try this instead:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Dim HiddenFileName As String
HiddenFileName = ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name
ThisWorkbook.Saved = True
On Error Resume Next
If Not (Left(ThisWorkbook.Name, 2) = "Z_") Then
Application.DisplayAlerts = False
' Unhide and delete existing file
SetAttr HiddenFileName, vbNormal
Kill HiddenFileName
' Save new copy and hide it
ThisWorkbook.SaveCopyAs HiddenFileName
SetAttr HiddenFileName, vbHidden
Application.DisplayAlerts = True
End If
SetAttr HiddenFileName, vbHidden
End Sub
It unhides and deletes the file, before creating it again. This is a bit dirty, since it doesn't test if it exists before, but relies on On Error Resume Next.

Export to CSV without opening

I am using an Excel Macro that detects two worksheets and writes them to CSV format in their current SharePoint directory. However, upon executing the macro, it proceeds to open the newly created files within the same workbook and gives me the following error:
Run-time error '1004':
Sorry, we couldn't find C:\ProgramFiles(x86)\Google\Chrome\Application...
Is it possible it was moved, renamed or deleted?
Can I perform the "Save As" without opening the new file and avoiding the given error?
To be clear, it performs the core function just fine, as the new CSV files are properly written to the Sharepoint folder, I simply want to avoid the error message.
Macro code is as below:
Sub Export()
'
' Export Macro
' Export Rules and Privileges to 'Rules.csv' and Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.Activate
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.Activate
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Range("B9").Select
Application.Run "RulesWorkbook.xlsm!Export"
Range("B4").Select
End Sub
Thank you to FreeMan for the solution in getting rid of the error message. While I did not figure out how to prevent Excel from opening the newly generated programs, I was able to side-step that by closing the workbook upon macro execution. Updated code for the macro is below:
Sub Export()
'
' Export Macro
' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub

Run-time error 1004 in Excel macro

I have an excel file that I use to create invoices and a macro used to save the workbook to a new file and cleared contents etc ready for the next invoice input.
Since upgrading to Windows 10 and MS Office 365 the macro has stopped working. I am far from an expert, I cobbled together several bits from the net and managed to create a macro that worked - before the upgrade!
I am getting a Run-time error "1004" Method 'Save As" of object '_workbook' failed.
The macro is
Sub NextInvoice()
Range("D3").Value = Range("D3").Value + 1
Range("B18:H43").ClearContents
End Sub
Sub SaveInvoiceNewName()
Dim NewFN As Variant
'Copy invoice to a new workbook
ActiveSheet.Copy
NewFN = "C:\This PC\Documents\Brewing\Invoices\Invoice " & Range("C5").Value & Range("D3").Value & ".xlsm"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXLSMWorkbookMacroEnabled
ActiveWorkbook.Close
NextInvoice
End Sub
There is no such thing as xlOpenXLSMWorkbookMacroEnabled. I believe you meant xlOpenXMLWorkbookMacroEnabled.
'let the FileFormat add the appropriate file extension.
NewFN = "C:\This PC\Documents\Brewing\Invoices\Invoice " & Range("C5").Value & Range("D3").Value
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbookMacroEnabled
See xlFileFormat Enumeration.

Resources