VBA SaveAs to .xlsm does not contain any macro modules - excel

I have a function that basically makes a copy of the current file, and save it to users' "Downloads" folder.
However, while the SaveAs works, the output does not contain any modules. Instead, they are all linked to the exporting file.
Sub PushToProduction()
Application.ScreenUpdating = False
' save a copy of current file to the Downloads folder
outputPath = Environ$("USERPROFILE") & "\Downloads\"
d = Format(Date, "yyyymmdd")
fileName = outputPath & "REDACTED " & d & " v1.00.xlsm"
' prepare to save a copy of the file without the last tab
sheetCount = Application.Sheets.Count - 1
Dim tabs() As String
ReDim tabs(1 To sheetCount)
For i = 1 To sheetCount
tabs(i) = Worksheets(i).Name
Next
Worksheets(tabs).Copy
ActiveWorkbook.SaveAs fileName, XlFileFormat.xlOpenXMLWorkbookMacroEnabled
ActiveWorkbook.Close False
Application.CutCopyMode = False
Application.ScreenUpdating = True
MsgBox ("Success!")
End Sub
The output does not even have the "Modules" folder.
Is there anyway to solve this?

Create a Workbook Copy and Modify It
Option Explicit
Sub PushToProduction()
Dim dFolderPath As String
dFolderPath = Environ$("USERPROFILE") & "\Downloads\"
Dim d As String: d = Format(Date, "yyyymmdd")
Dim dFilePath As String
dFilePath = dFolderPath & "REDACTED " & d & " v1.00.xlsm"
Application.ScreenUpdating = False
' Create a reference to the Source Workbook ('swb').
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
' Save a copy of the Source Workbook.
If StrComp(dFilePath, swb.FullName, vbTextCompare) = 0 Then
MsgBox "You are trying save a copy of the file to the same location.", _
vbCritical, "Push to Production"
Exit Sub
End If
swb.SaveCopyAs dFilePath
' Open the copy, the Destination Workbook ('dwb'), remove its last sheet
' and close saving the changes.
Dim dwb As Workbook: Set dwb = Workbooks.Open(dFilePath)
Application.DisplayAlerts = False
dwb.Sheets(dwb.Sheets.Count).Delete
Application.DisplayAlerts = True
dwb.Close SaveChanges:=True
Application.ScreenUpdating = True
' Inform.
MsgBox "Success!", vbInformation, "Push to Production"
' Explore Destination Folder.
'swb.FollowHyperlink dFolderPath
End Sub

Related

Create another file but don't split worksheets into separate files

Separate worksheets into separate files
Hi I am using code
Sub Split_Sheet_into_ExcelFiles()
Dim FilePath As String
FilePath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each Sheet In ThisWorkbook.Sheets
Sheet.Copy
Application.ActiveWorkbook.SaveAs Filename:=FilePath & "\" & Sheet.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
It creates the same file but I was trying to split multiple worksheets into individual files. ANy idea what I'm typing wrong? Thanks
Export Each Sheet to an Individual File
Option Explicit
Sub ExportSheets()
Const PROC_TITLE As String = "Export Sheets"
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim dFilePath As String: dFilePath = swb.Path
If Len(dFilePath) = 0 Then
MsgBox "The path cannot be determined." & vbLf & "Please save the " _
& "workbook before using this procedure.", vbCritical, PROC_TITLE
Exit Sub
End If
Application.ScreenUpdating = False
Dim dwb As Workbook, ssh As Object, sshCount As Long
For Each ssh In swb.Sheets
If ssh.Visible = xlSheetVisible Then ' sheet is visible
ssh.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs Filename:=dFilePath & "\" & ssh.Name
Application.DisplayAlerts = False
dwb.Close SaveChanges:=False
sshCount = sshCount + 1
'Else ' sheet is not visible; do nothing!?
End If
Next ssh
Application.ScreenUpdating = True
MsgBox sshCount & " sheet" & IIf(sshCount = 1, "", "s") _
& " exported.", vbInformation, PROC_TITLE
End Sub

Workbook.Activate method

i got a variable:
V_WBNameOutPut as string
and use it inside the following code:
Application.Workbooks(V_WBNameOutPut).Activate
This two part of code are inside a huger code which work fine for 99.99% of different users, but only for one user the code go in error and when I debug its stop to Application.Workbooks(V_WBNameOutPut).Activate line.
And the error is the following:
Runtime Error 9: Subscript Out of Range
Any ideas why this happend and possible solution?
Thanks
I try it to debug but the code works fine but for one particular user it doesn't
The subroutine to generate the output file, which the Application.Workbooks(V_WBNameOutPut).Activate refers to:
Sub CreateWB()
Dim File_Name As Variant
Dim File_Name_Saved As String
Dim i_attempt As Integer
Dim NewWorkBook As Workbook
Set NewWorkBook = Workbooks.Add
Do While i_attempt < 2
i_attempt = i_attempt + 1
File_Name = Application.GetSaveAsFilename(InitialFileName:=V_WBNameOutPut, filefilter:="Excel Files(*.xlsx),*.xlsx,Excel-Macro Files (*.xlsm),*.xlsm", Title:="Please choose a Folder")
File_Name_Saved = Left(Right(File_Name, Len(V_WBNameOutPut) + 5), Len(V_WBNameOutPut))
If File_Name = False Then
ActiveWorkbook.Close
End
Else
If UCase(File_Name_Saved) <> UCase(V_WBNameOutPut) Then
If i_attempt < 2 Then
MsgBox "Please do not change the File name" & vbCrLf & i_attempt & "/2 Attempt"
Else
ActiveWorkbook.Close
End
End If
Else
Application.DisplayAlerts = False
NewWorkBook.SaveAs File_Name, ConflictResolution:=True
Exit Do
End If
End If
Loop
End Sub
You can loop through the open workbooks looking for a match without the file extension. A better solution would be to make CreateWB a function that returns the saved filename.
Option Explicit
Dim V_WBNameOutPut
Sub test()
Dim wb As Workbook
V_WBNameOutPut = "test2"
CreateWB
For Each wb In Workbooks
If wb.Name Like V_WBNameOutPut & "*" Then
wb.Activate
Exit For
End If
Next
Sheets(1).Cells(1, 1).Select ' active workbook
End Sub
Sub CreateWB()
Dim NewWorkBook As Workbook
Dim fso As Object, bSaveOK As Boolean, i_attempt As Integer
Dim File_Name As Variant, File_Name_Saved As String
Set fso = CreateObject("Scripting.FileSystemObject")
For i_attempt = 1 To 2
File_Name = Application.GetSaveAsFilename( _
InitialFileName:=V_WBNameOutPut, _
filefilter:="Excel Files(*.xlsx),*.xlsx,Excel-Macro Files (*.xlsm),*.xlsm", _
Title:="Please choose a Folder")
If File_Name = False Then Exit Sub
bSaveOK = (fso.getbasename(File_Name) = V_WBNameOutPut)
If Not bSaveOK And i_attempt = 1 Then
MsgBox "Please do not change the File name from " & V_WBNameOutPut _
& vbCrLf & i_attempt & "/2 Attempt"
Else
Exit For
End If
Next
' create workbook and save
If bSaveOK Then
Set NewWorkBook = Workbooks.Add
Application.DisplayAlerts = False
NewWorkBook.SaveAs File_Name, ConflictResolution:=True
Application.DisplayAlerts = True
End If
End Sub

saving sheets from a new workbook excel

i have an issue with this code. I need to save the data from a workbook to a new workbook but the new workbook doesn't save, I do it manually. I need it to save automatically. Any idea what is going on?
this is my code so far
Private Sub CommandButton3_Click()
Dim wb As Workbook
Dim wb_New As Workbook
Set wb = ThisWorkbook
Dim wbstring As String
Dim input_file_name As String
input_file_name = InputBox("Enter file name", "Enter new workbook file name")
wbstring = "C:\PIME\\"
Workbooks.Add.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Set wb_New = ActiveWorkbook
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
End Sub
You got it almost right - Set wb_New to the new workbook, populate the data then use SaveAs method.
Set wb_New = Workbooks.Add
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
wb_New.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Copy a Range to a New One-Worksheet Workbook
The only mistake I could find was that you need to remove one of the two trailing backslashes from the path:
wbstring = "C:\PIME\"
An Improvement
Option Explicit
Private Sub CommandButton3_Click()
' Source
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets("NUMB")
' Destination
Dim dFolderPath As String: dFolderPath = "C:\PIME\"
If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
Dim dExtension As String: dExtension = ".xls"
If Left(dExtension, 1) <> "." Then dExtension = "." & dExtension
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then
MsgBox "The path '" & dFolderPath & "' doesn't exist.", vbCritical
Exit Sub
End If
Dim dFileName As String
dFileName = InputBox("Enter file name", "Enter new workbook file name")
If Len(dFileName) = 0 Then
MsgBox "Canceled or no entry."
Exit Sub
End If
Dim dwb As Workbook: Set dwb = Workbooks.Add(xlWBATWorksheet) ' single...
Dim dws As Worksheet: Set dws = dwb.Worksheets(1) ' ... worksheet,...
' ... in another language it may not be 'Sheet1'.
' Copy by Assignement (the most efficient way to copy only values)
dws.Range("A1:I2000").Value = sws.Range("A1:I2000").Value
' Save(As)
Dim dFilePath As String: dFilePath = dFolderPath & dFileName & dExtension
Dim ErrNum As Long
Application.DisplayAlerts = False ' overwrite without confirmation
On Error Resume Next
dwb.SaveAs Filename:=dFilePath, FileFormat:=xlExcel8 ' or 56
ErrNum = Err.Number
On Error GoTo 0
Application.DisplayAlerts = True
' Close
dwb.Close SaveChanges:=False
' Inform
If ErrNum = 0 Then
MsgBox "File saved.", vbInformation
Else
MsgBox "Could not save the file.", vbCritical
End If
End Sub
You may tweak your code as below...
Workbooks.Add.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Set wb_New = ActiveWorkbook
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
'Then either use wbNew.Save or wbNew.Close True as per your need
wbNew.Save 'To save the work and leave the new workbook open
'OR
wbNew.Close True 'To save the work and close the new workbook.

Excel crashing when I run VBA macro

I have a workbook with a VBA macro that I run every day where I paste a large set of data and it formats, fills in extra fields using a vlookup against hidden sheets, splits the data into individual sheets, and saves each as a CSV file.
This process runs perfectly 6 out 7 days of the week & only has issues when I run Sunday data.
All VBA macros within the workbook work fine until I get to the step where it saves the CSVs, then it force closes the excel workbook.
I've noticed it saves 1 worksheet (named RCM), but even that it does incorrectly as it only pulls the first row into the file, and the row is from the incorrect sheet.
I thought the issue was with the sheet name (as I have a hidden sheet named RCM1 and the hidden sheets do not get saved). But I've attempted renaming the sheets & am still having the same issue.
I'm now uncertain of what is causing Excel to crash only with this particular data.
Here is the save portion of the macro
Sub SaveSheets()
'
' SaveSheets Macro
' Saves sheets as individual CSV files
'
'
Dim csvPath As String
Dim DateName As String
csvPath = "C:\Daily Batch Files"
r = Worksheets("Data").Range("B2")
DateName = "batchredeem.001." & WorksheetFunction.Text(r, "mmmmdd") & "_"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Work").ShowAllData
For Each xWs In ThisWorkbook.Sheets
If xWs.Visible = xlSheetVisible And xWs.Name <> "Magic Buttons" And xWs.Name <> "Data" And xWs.Name <> "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & DateName & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
ElseIf xWs.Name = "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
**EDIT to add additional info:
If I change the name of the sheet before running the macro, it won't save the renamed "RCM" sheet at all- it works for the previous sheet, however, and if I delete the "RCM" sheet, the entire macro runs normally.
***EDIT 2 - I also cannot manually "copy" the "RCM" sheet, but I can manually copy any of the others. Also, if I save the entire workbook, then run the macro, it works normally! I'm stumped & not sure why it isn't working just for this one worksheet.
Export Worksheets As One-Worksheet Files
Option Explicit
Sub ExportVisibleWorksheets()
' Saves worksheets as individual CSV files
' Source
Const sExceptionsList As String = "Magic Buttons,Work,Data"
Const sSpecialName As String = "Work" ' exported differently
' Source Lookup
Const slName As String = "Data" ' included in the exceptions list
Const slCellAddress As String = "B2"
' Destination
Const dDateLeft As String = "batchredeem.001."
Const dDateMidFormat As String = "mmmmdd"
Const dDateRight As String = "_"
Dim dFolderPath As String: dFolderPath = "C:\Daily Batch Files\"
' The following two depend on each other!
Dim dFileExtension As String: dFileExtension = ".csv"
Dim dFileFormat As XlFileFormat: dFileFormat = xlCSV
If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then Exit Sub ' doesn't exist
If Left(dFileExtension, 1) <> "." Then dFileExtension = "." & dFileExtension
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets(slName)
Dim sCell As Range: Set sCell = sws.Range(slCellAddress)
Dim sExceptions() As String: sExceptions = Split(sExceptionsList, ",")
Dim dDateMid As String
dDateMid = WorksheetFunction.Text(sCell.Value, dDateMidFormat) ' English
'dDateMid = Format(sCell.Value, dDateMidFormat) ' International
Dim dDateName As String: dDateName = dDateLeft & dDateMid & dDateRight
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim dFilePath As String
Dim dwsCount As Long
Dim ErrNum As Long
Dim DoNotCopy As Boolean
For Each sws In swb.Worksheets
If sws.Visible = xlSheetVisible Then
If IsError(Application.Match(sws.Name, sExceptions, 0)) Then
dFilePath = dFolderPath & dDateName & sws.Name & dFileExtension
ElseIf StrComp(sws.Name, sSpecialName, vbTextCompare) = 0 Then
dFilePath = dFolderPath & sws.Name & dFileExtension
If sws.AutoFilterMode Then
sws.ShowAllData
End If
Else
DoNotCopy = True
End If
If DoNotCopy Then
DoNotCopy = False
Else
sws.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite: no confirmation
On Error Resume Next ' prevent error if file is open
dwb.SaveAs Filename:=dFilePath, FileFormat:=dFileFormat
ErrNum = Err.Number
On Error GoTo 0
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
If ErrNum = 0 Then
dwsCount = dwsCount + 1
Else
ErrNum = 0
End If
End If
End If
Next
Application.ScreenUpdating = True
Select Case dwsCount
Case 0: MsgBox "No worksheets exported.", vbExclamation
Case 1: MsgBox "One visible worksheet exported.", vbInformation
Case Else
MsgBox dwsCount & " visible worksheets exported.", vbInformation
End Select
End Sub

VBA to copy workbook and keep relative cell references between sheets

I have workbook that has multiple sheets and need a macro button to save a copy of it and delete the sheet named "CSG". This was easy to do, but the problem was that all cell references pointed to the original workbook.
With help, the problem has been tried to solve through name manager and break all links-code. Now the problem is that it break all references within the new workbook and copies only the values from the original workbook.
For example, in the original workbook sheet1 cell A1 has value 10, sheet2 cell A1 has cell reference "='sheet1'!A1". When I make the new copy, both cells do have the value 10, but the reference is no longer there.
Is there a way to keep these references within the workbook without them referencing the original workbook? Below is the code currently being used.
Sub SaveTest()
Dim x As Integer
Dim FileName As String, FilePath As String
Dim NewWorkBook As Workbook, OldWorkBook As Workbook
Set OldWorkBook = ThisWorkbook
With Application
.ScreenUpdating = False: .DisplayAlerts = False
End With
On Error Resume Next
With OldWorkBook.Sheets("CSG")
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " & .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
MkDir FilePath
On Error GoTo -1
On Error GoTo myerror
FilePath = FilePath & "\"
For x = 2 To OldWorkBook.Worksheets.Count
With OldWorkBook.Worksheets(x)
If Not NewWorkBook Is Nothing Then
.Copy after:=NewWorkBook.Worksheets(NewWorkBook.Worksheets.Count)
Else
.Copy
Set NewWorkBook = ActiveWorkbook
End If
End With
Next x
DeleteBadNames NewWorkBook
BreakAllLinks NewWorkBook
UpdateNameManager NewWorkBook
NewWorkBook.SaveAs FilePath & FileName, 51
myerror:
If Not NewWorkBook Is Nothing Then NewWorkBook.Close False
With Application
.ScreenUpdating = True: .DisplayAlerts = True
End With
If Err <> 0 Then MsgBox (Error(Err)), 48, "Error"
End Sub
Create a Copy of a Workbook
Option Explicit
Sub SaveTest()
Dim OldWorkBook As Workbook: Set OldWorkBook = ThisWorkbook
Dim WorkSheetNames() As String
Dim FilePath As String
Dim FileName As String
With OldWorkBook.Worksheets("CSG")
ReDim WorkSheetNames(1 To .Parent.Worksheets.Count)
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " _
& .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
On Error Resume Next
MkDir FilePath
On Error GoTo 0
FilePath = FilePath & "\"
Dim ws As Worksheet
Dim n As Long
For Each ws In OldWorkBook.Worksheets
n = n + 1
WorkSheetNames(n) = ws.Name
Next ws
Application.ScreenUpdating = False
OldWorkBook.Worksheets(WorkSheetNames).Copy
With ActiveWorkbook ' new workbook
Application.DisplayAlerts = False
.Worksheets("CSG").Delete
.SaveAs FilePath & FileName, 51 ' xlOpenXMLWorkbook
Application.DisplayAlerts = True
'.Close SaveChanges:=False
End With
Application.ScreenUpdating = True
End Sub

Resources