vba - workaround for issue excel saving temp files - vba

When saving a specific workbook, Excel creates a temp file instead of saving the data (without displaying an error or warning message). The symptoms are roughly the same as described in this post:
microsoft-excel-returns-the-error-document-not-saved-after-generating-a-2gb-temp-file
I tried several solutions, but decided to implement a work-around as ‘save as’ is working ok.
The code below performs the ‘save-as’, based on having filenames ending with a value (e.g. myFile V1.xlsm), the macro will add an incremental character (a to z) each time the workbook is saved. (e.g. myFile V1a.xlsm).
The macro works fine in a standard module, but it causes Excel to “stop responding” when moved to ‘thisWorkbook’. I ‘solved’ this by keeping it in the standard module and assigning key combination ‘control-s’ to the macro. Still interested to know if it can be made to work in the ‘thisWorkbook’.
Drawback of this workaround is that each incremental save clogs up the ‘recent file’ list. It would be nice to remove the previous file name from the recent file history, but this seems not possible to do via VBA. (VBA - How do I remove a file from the recent documents list in excel 2007?). Any suggestions?
Windows 10, Excel 2016 (version 16.0.6868.2060)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim newFilename As String
Dim oldFilename As String
oldFilename = ActiveWorkbook.Name
newFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
If IsNumeric(Right(newFilename, 1)) = True Then
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & "a.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
If Right(newFilename, 1) = "z" Then
MsgBox "'z' reached, please save as new version"
Exit Sub
End If
newFilename = Left(newFilename, Len(newFilename) - 1) & Chr(Asc(Right(newFilename, 1)) + 1)
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End If
'potential code to remove oldFilename from 'Recent File' list
End Sub

I tested this Sub in Excel 2010 and it works for me. I immediately break the loop after deleting the file as I assume the indexing may get out of alignment with the loop. A more refined variant might loop through the recent file list and create a collection of indices to delete, then iterate backward over that collection and delete each entry in turn.
Public Sub RemoveRecentFile(strFileName As String)
Dim collRecentFiles As Excel.RecentFiles
Dim objRecentFile As Excel.RecentFile
Dim intRecentFileCount As Integer
Dim intCounter As Integer
Set collRecentFiles = Application.RecentFiles
intRecentFileCount = collRecentFiles.Count
For intCounter = 1 To intRecentFileCount
Set objRecentFile = collRecentFiles(intCounter)
If objRecentFile.Name = strFileName Then
objRecentFile.Delete
Exit For
End If
Next intCounter
End Sub

Thanks to Robin the working solution is as follows:
Updated intial code:
Sub incrementSaveAs()
'to avoid that other workbooks are saved (when assigned to shortkey control-S)
If ActiveWorkbook.Name <> ThisWorkbook.Name Then ActiveWorkbook.Save: Exit Sub
Dim newFilename As String
Dim oldFilename As String
oldFilename = ActiveWorkbook.Name
newFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
If IsNumeric(Right(newFilename, 1)) = True Then
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & "a.xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False, AddToMru:=True
'AddToMru:=True Added to update recent files history
Else
If Right(newFilename, 1) = "z" Then
MsgBox "'z' reached, please save as new version"
Exit Sub
End If
newFilename = Left(newFilename, Len(newFilename) - 1) & Chr(Asc(Right(newFilename, 1)) + 1)
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False, AddToMru:=True
End If
RemoveRecentFile (ActiveWorkbook.Path & Application.PathSeparator & oldFilename)
End Sub
Updated Robin's code:
Public Sub RemoveRecentFile(strPathAndFileName As String)
Dim collRecentFiles As Excel.RecentFiles
Dim objRecentFile As Excel.RecentFile
Dim intRecentFileCount As Integer
Dim intCounter As Integer
Set collRecentFiles = Application.RecentFiles
intRecentFileCount = collRecentFiles.Count
For intCounter = 1 To intRecentFileCount
Set objRecentFile = collRecentFiles(intCounter)
If objRecentFile.Path = strPathAndFileName Then
objRecentFile.Delete
Exit For
End If
Next intCounter
End Sub

Related

Email loop causing Notes to crash (Embed object = issue)

I have the following code which is always causing IBM(LOTUS) Notes to crash at the .EmbedObject line
Call body.EmbedObject(1454, "", Attachment)
This is the part of the main code. At this point there are 2 dictionaries which are converted to arrays and then into e-mail strings. The call to the EMAIL sub-routine is below.
Anyone have any idea what could be causing this or know a fix?? All variables are declared at the public level in the main module with string type
This works fine with a simple loop macro that I used to integrate into my macro (basic for loop calling the email routine every iteration, with declaring the document and body each time)
thank you
Private Sub SaveFilestoDesktop_andEmail()
'Saves file to desktop with date stamp and e-mails to the user
Dim WB As Workbook
Dim wks As String
Dim fname As String, i As Integer
Dim EmailArray_PC() As Variant, EmailArray_PM() As Variant
EmailArray_PM = dict.keys()
EmailArray_PC = dict_2.keys()
i = 1
Subj = "Items to Review"
'EmailBody = "The following items have been flagged as possible cost errors " & _
'"by process of identifying variances of +/- 30 % compared to the current average cost. " & _
'"Please see attachment and review for internal purposes." & vbLf & _
'vbLf & VBA.Format(Now, "m/d/yyyy hh:mm:ss AM/PM")
On Error GoTo errhandlr
For Each WB In Workbooks
'Set the first sheet name of each WB to the wks variable
wks = WB.ActiveSheet.Name
'If unsaved workbook (only part of the above sub procedures)
If Left(WB.Name, 4) = "Book" Then
fname = Application.DefaultFilePath & "\" & Replace(WB.Worksheets(1).Name, ".", "") & "- " & VBA.FormatDateTime(Date, vbLongDate) _
& " (" & Format(Time, "hhmmss AMPM") & ")"
With WB
' If Dir(fname) <> "" Then
Application.DisplayAlerts = False
'Save the file as an .xlsx to the default user path
.SaveAs Filename:=fname, FileFormat:=51
Application.DisplayAlerts = True
On Error Resume Next 'if tries to e-mail but it fails (such as for "blank")
'Setting up parameters for e-mailing
SendTo = Right(EmailArray_PM(i), Len(EmailArray_PM(i)) - WorksheetFunction.Find(",", EmailArray_PM(i)) - 1) & "_" & _
Left(EmailArray_PM(i), WorksheetFunction.Find(",", EmailArray_PM(i)) - 1) & "#quadra.ca"
SendCC = Right(EmailArray_PC(i), Len(EmailArray_PC(i)) - WorksheetFunction.Find(",", EmailArray_PC(i)) - 1) & _
"_" & Left(EmailArray_PC(i), WorksheetFunction.Find(",", EmailArray_PC(i)) - 1) & "#quadra.ca"
Attachment = WB.Name
'Call e-mail maco in Other module
Call Email_using_Notes_Call(SendTo, SendCC, Attachment)
'Increment i by 1
i = i + 1
On Error GoTo 0
'Close the Workbook, go to next WB
.Close
End With
'Clear the filename to save with for next WB
fname = Empty
End If
Next WB
Exit Sub
Erase EmailArray_PC: Erase EmailArray_PM
Set dict = Nothing: Set dict_2 = Nothing 'clear dict objs
errhandlr:
MsgBox err.Number & Space(2) & err.Description
err.Clear
'MsgBox err.Number & Space(2) & err.Description
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Call to EMAIL loop:
Sub Email_using_Notes_Call(ByVal SendTo As String, _
Optional ByVal SendCC As String, Optional ByVal Attachment As String)
On Error Resume Next
'Creates the Notes Document (e-mail)
Set doc = db.CreateDocument
With doc
.Subject = Subj
.SendTo = SendTo
.CopyTo = SendCC
.Importance = "1"
End With
'Creating the body of the Notes document
Set body = doc.CreateRichTextItem("Body")
'Formatting the body of the text
Call body.AppendText("The following items have been flagged as possible cost errors by process of identifying variances of +/- 30 %")
Call body.AddNewline(1) '--> This adds a line feed to the body
Call body.AppendText("compared to the current average cost. Please see attachment and review for internal purposes ")
Call body.EmbedObject(1454, "", Attachment) --> this is where it crashes 'EMBED_ATTACHMENT[1454 = embed attachment, 1453 = embed object]
Call body.AddNewline(2)
Call body.AppendText(Now())
Call doc.Send(False) 'False is the variable that indicates attach form or not (always false in our case)
'Clearing for next document
Set body = Nothing
Set doc = Nothing
On Error GoTo -1
End Sub
I think this issue is caused what you are trying to embed.
The document you are trying to Embed is the Excel workbook itself. You have the workbook open, so it cannot necessarily be read due to a lock.
Something that might help you definitely find out if that's the reason:
Try to add another file as the attachment that isn't open and see if it works, as a test.
Change the On Error Resume Next located in your e-mailing function to an error handler, like you have in the function above it.

How to open a new workbook and add images with VBA?

I'm trying to get a macro for Excel 2007to open a folder with a bunch of images in them. Then Create a new workbook and embed the images into it.
Everything works if I comment out the line Sheet.Shapes.AddPicture FileName:=F, linktofile:=msoFalse, savewithdocument:=msoCTrue, Left:=cell.Left + 5, Top:=cell.Top + 5, Width:=560, Height:=310 If I uncomment that line I get "Run-time error '434': Object required"
I've check that Sheet.Shapes is returning a Shapes object, it is but the Shapes object is empty. When I try Sheet.Shapes,AddPicture on a workbook that is opened outside of the macro, it adds the images. I've also checked that Sheet.Shapes.AddShape works with the workbook opened in the macro, it does.
At this point, I'm at a lose for what the issue might be. Does anyone have any experience with this sort of thing? Should I be using a different method? Thanks in advance for any help or guidance.
Sub Macro1()
Dim ImagePath, Flist
ImagePath = GetFolder()
If ImagePath = "" Then Exit Sub
Flist = FileList(ImagePath)
Name = "C:\target.xlsm"
Set Book = Workbooks.Add
Set Sheet = Book.Sheets(1)
For i = 1 To 5
cell = "C" + CStr(i)
F = ImagePath + "\" + Flist(i - 1)
Sheet.Shapes.AddPicture FileName:=F, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=cell.Left + 5, Top:=cell.Top + 5, Width:=560, Height:=310
Next
Book.SaveAs FileName:=Name, FileFormat:=52
Book.Close
End Sub
Function FileList(ByVal fldr As String) As Variant
'Lists all the files in the current directory
'Found at http://www.ozgrid.com/forum/showthread.php?t=71409
Dim sTemp As String, sHldr As String
If Right$(fldr, 1) <> "\" Then fldr = fldr & "\"
sTemp = Dir(fldr & "*.png")
If sTemp = "" Then
FileList = False
Exit Function
End If
Do
sHldr = Dir
If sHldr = "" Then Exit Do
sTemp = sTemp & "|" & sHldr
Loop
FileList = Split(sTemp, "|")
End Function
Function GetFolder() As String
Folder:
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "New Screenshot Folder"
.Show
num = .SelectedItems.Count
If .SelectedItems.Count = 0 Then
GetFolder = ""
Else: GetFolder = .SelectedItems(1)
End If
End With
End Function
You can't define a cell by creating the string "C1", that's just the address. The way you did it, cell is a string and a string doesn't have any properties. What you want is a range object so either use
Dim cell As Range
Set cell = sheet.Range("C" & i)
or
Dim cell As Range
Set cell = sheet.Cells(i, 3)
You should always Dim all variables, use Option Explicit on top of your module so you don't forget it ;)
This will often prevent mistakes. Of course you should Dim them with the correct type, i.e. Dim FilePath As String.
The correct command would be:
Sheet.Shapes.AddPicture Filename:=F, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=Range(cell).Left + 5, Top:=Range(cell).Top + 5, Width:=560, Height:=310
I strongly advise you to change your Name variable name, as it will cause errors on recent versions of excel.

ActiveWorkbook.SaveAS filename:= using special characters

Admittedly I'm bad at knowing the lingo, so while I think I researched this thoroughly, there may be the perfect answer somewhere. Here's my dilemma, I'm developing this Excel VBA macro to backup and restore the Worksheet (basically giving me infinite Undos to the point I specify and short-cutting around saving and reopening):
Public BULast As String
Sub Backup()
'This macro imitates videogame save-states. It will save a backup that can replace to current workbook later if you've made an irreversible mistake.
'Step 1: Agree to run away if things go wrong (establish an error handler)
On Error GoTo BackupError
'Step 2: Create some variables
Dim OriginalFile As String
Dim BUDir As String
Dim BUXAr() As String
Dim BUExt As String
Dim BUNam As String
Dim BackupFile As String
'Step 3: Define those variables
OriginalFile = ActiveWorkbook.FullName
BUDir = ActiveWorkbook.Path
BUXAr = Split(ActiveWorkbook.FullName, ".")
BUExt = BUXAr(UBound(BUXAr))
BUNam = Replace(ActiveWorkbook.Name, "." & BUExt, "") & " (Back-Up)"
BackupFile = BUDir & "\" & BUNam & "." & BUExt
'Step 4: Hide the truth
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Step 5(A): If there is no backup file, create one using the same file name as the one you're working with and throw a " (Back-up)" on it.
If Dir(BackupFile) = "" Then
ActiveWorkbook.SaveAs filename:=BackupFile
ActiveWorkbook.Close
Workbooks.Open filename:=OriginalFile
BUYoN = vbNo
BULast = Date & ", " & Time
MsgBox "A Backup has been created!"
Else
BUYoN = MsgBox("This will restore the " & BULast & " backup and undo all changes made to this project. Continue?" _
, vbYesNo, "Revert to Backup?")
End If
'Step 5(B): If a backup has been created, restore it over the current workbook and delete the backup.
If BUYoN = vbYes Then
ActiveWorkbook.Close
Workbooks.Open filename:=BackupFile
ActiveWorkbook.SaveAs filename:=OriginalFile
Kill (BackupFile)
BUCheck = "Dead"
End If
'Step 6: Put things back to the way you found them, you're done!
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
'Step 1 (Continued): If nothing went wrong, stop worrying about it, if something did, say it didn't work and go away.
On Error GoTo 0
BackupError:
MsgBox "Attempt to Backup or Restore was unsuccessful"
End Sub
Normally it works as expected, but just yesterday it started not working and after playing around with it I realized it's because I was trying it on a file that has an Ω symbol in the file name.
The basic process is to look in the current directory for the active workbook's file name, but with (Back-up) tacked at the end. It will either create one, or replace the open one with what it finds. When done on an Ω file however, it substitutes that character with an O. When ran again, it apparently searches the the Ω correctly because it can't find any (even with the O-substitute file right there in plain sight).
I know the easiest solution would be to just make sure people keep their file names to what you can see on a keyboard, but that doesn't work for me; I'm almost religious about putting the adaptability in the code rather than the user. So with that long-winded back story, here's my specific question:
Is there a SaveAs function or practical workaround in VBA that can handle special characters within the specified file name?
The problem lies in the Dir() function as it converts the special characters to ANSI before checking for the file and thus fails for these cases. Use the FileSystemObject object instead:
Sub Backup()
On Error GoTo BackupError
Dim OriginalFile As String
OriginalFile = ActiveWorkbook.FullName
' get back up file name
Dim BackupFile As String
Dim pos As Integer
pos = InStrRev(OriginalFile, ".")
BackupFile = Mid$(OriginalFile, 1, pos - 1) & " (Back-Up)." & Mid$(OriginalFile, pos + 1)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Step 5(A): If there is no backup file, create one using the same file name as the one you're working with and throw a " (Back-up)" on it.
Dim BUYoN As VbMsgBoxResult
Dim BULast As String
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
With fs
If Not .FileExists(BackupFile) Then
ActiveWorkbook.SaveAs Filename:=BackupFile
ActiveWorkbook.Close
Workbooks.Open Filename:=OriginalFile
BUYoN = vbNo
BULast = Date & ", " & Time
MsgBox "A Backup has been created!"
Else
BUYoN = MsgBox("This will restore the " & BULast & " backup and undo all changes made to this project. Continue?" _
, vbYesNo, "Revert to Backup?")
End If
End With
'Step 5(B): If a backup has been created, restore it over the current workbook and delete the backup.
If BUYoN = vbYes Then
ActiveWorkbook.Close
Workbooks.Open Filename:=BackupFile
ActiveWorkbook.SaveAs Filename:=OriginalFile
'Kill (BackupFile)
fs.Delete BackupFile
Dim BUCheck As String
BUCheck = "Dead"
End If
'Step 6: Put things back to the way you found them, you're done!
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
On Error GoTo 0
BackupError:
MsgBox "Attempt to Backup or Restore was unsuccessful"
End Sub
I know we're not supposed to offer opinions, but it is my opinion that Rachel is a genius! I didn't know about the FileSystemObject, but that ended up being the key. Not only was it able to search for and recognized the file with special characters, but it appears it can delete it too. Incorporating that into the code makes it run flawlessly with or without special characters:
Public BULast As String
Sub Backup()
'This macro imitates videogame save-states. It will save a backup that can replace the
'current workbook later if you've made an irreversible mistake.
'Step 1: Agree to run away if things go wrong (establish an error handler)
On Error GoTo BackupError
'Step 2: Create some variables
Dim OriginalFile As String
Dim BUDir As String
Dim BUXAr() As String
Dim BUExt As String
Dim BUNam As String
Dim BackupFile As String
Dim BUfs As Object
'Step 3: Define those variables
OriginalFile = ActiveWorkbook.FullName
BUDir = ActiveWorkbook.Path
BUXAr = Split(ActiveWorkbook.FullName, ".")
BUExt = BUXAr(UBound(BUXAr))
BUNam = Replace(ActiveWorkbook.Name, "." & BUExt, "") & " (Back-Up)"
BackupFile = BUDir & "\" & BUNam & "." & BUExt
Set BUfs = CreateObject("Scripting.FileSystemObject")
'Step 4: Hide the truth
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Step 5(A): If there is no backup file, create one using the same file name as the one
'you're working with and throw a " (Back-up)" on it.
With BUfs
If Not .FileExists(BackupFile) Then
ActiveWorkbook.Save
ActiveWorkbook.SaveAs filename:=BackupFile
ActiveWorkbook.Close
Workbooks.Open filename:=OriginalFile
BUYoN = vbNo
BULast = Date & ", " & Time
MsgBox "A Backup has been created!"
Else
BUYoN = MsgBox("This will restore the " & BULast & " backup and undo all changes made to this project. Continue?" _
, vbYesNo, "Revert to Backup?")
End If
End With
'Step 5(B): If a backup has been created, restore it over the current workbook and
'delete the backup.
If BUYoN = vbYes Then
ActiveWorkbook.Close
Workbooks.Open filename:=BackupFile
ActiveWorkbook.SaveAs filename:=OriginalFile
BUfs.DeleteFile BackupFile, True
End If
'Step 6: Put things back to the way you found them, you're done!
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
'Step 1 (Continued): If nothing went wrong, stop worrying about it, if something did,
'say it didn't work and go away.
On Error GoTo 0
BackupError:
MsgBox "Attempt to Backup or Restore was unsuccessful"
End Sub

Exporting PowerPoint sections into separate files

Every week I separate a long PowerPoint file into separate files. The files must be in PowerPoint format, and contain only the slides that are contained in the 'sections' from the PowerPoint file.
I need to:
1) Scan to see the number of slides in a given section
2) Make a file containing the slides within that section
3) Name that file the same as the name of the section, and save it in the same directory as the source file.
4) Repeat the process for subsequent sections.
5) Do this without damaging the original file.
I've located code (http://www.pptfaq.com/FAQ01086_Break_a_presentation_up_into_several_smaller_presentations.htm) that can break the file into many parts, but only by the number of files requested per file. I found some other helpful references here: http://skp.mvps.org/2010/ppt001.htm
I have coded in Basic and a number of easy gaming scripting languages. I need help understanding how this is done in VBA.
Since you do this very often, you should make an Add-In for this. The idea is to create copies of the presentation up to the number of sections in it, then open each one and delete the other sections and save.
Create blank presentation with macros enabled (*.pptm) and possibly add Custom UI button to call SplitIntoSectionFiles
Test and when satisfy, save as PowerPoint Add-In (*.ppam). Don't delete the pptm file!
Assuming that all are pptx files you are dealing with, you can use this code. It opens the splited pptx files in background, then remove irrelevant sections and save, close. If all goes well you get a message box.
Private Const PPT_EXT As String = ".pptx"
Sub SplitIntoSectionFiles()
On Error Resume Next
Dim aNewFiles() As Variant, sPath As String, i As Long
With ActivePresentation
sPath = .Path & "\"
For i = 1 To .SectionProperties.Count
ReDim Preserve aNewFiles(i)
' Store the Section Names
aNewFiles(i - 1) = .SectionProperties.Name(i)
' Force Save Copy as pptx format
.SaveCopyAs sPath & aNewFiles(i - 1), ppSaveAsOpenXMLPresentation
' Call Sub to Remove irrelevant sections
RemoveOtherSections sPath & aNewFiles(i - 1) & PPT_EXT
Next
If .SectionProperties.Count > 0 And Err.Number = 0 Then MsgBox "Successfully split " & .Name & " into " & UBound(aNewFiles) & " files."
End With
End Sub
Private Sub RemoveOtherSections(sPPT As String)
On Error Resume Next
Dim oPPT As Presentation, i As Long
Set oPPT = Presentations.Open(FileName:=sPPT, WithWindow:=msoFalse)
With oPPT
' Delete Sections from last to first
For i = .SectionProperties.Count To 1 Step -1
' Delete Sections that are not in the file name
If Not InStr(1, .Name, .SectionProperties.Name(i), vbTextCompare) = 1 Then
' Delete the Section, along with the slides associated with it
.SectionProperties.Delete i, True
End If
Next
.Save
.Close
End With
Set oPPT = Nothing
End Sub
Read about Custom UI if you don't have experience creating you own ribbon tab: msdn and use the "Office Custom UI Editor", I would use imageMso "CreateModule" for the button.
None of the proposed routines actually works, so I wrote mine from scratch:
Sub Split()
Dim original_pitch As Presentation
Set original_pitch = ActivePresentation
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
With original_pitch
.SaveCopyAs _
FileName:=fso.BuildPath(.Path, fso.GetBaseName(.Name) & ".pptx"), _
FileFormat:=ppSaveAsOpenXMLPresentation
End With
Dim i As Long
For i = 1 To original_pitch.SectionProperties.Count
Dim pitch_segment As Presentation
Set pitch_segment = Presentations.Open(Replace(original_pitch.FullName, "pptm", "pptx"))
section_name = pitch_segment.SectionProperties.Name(i)
For k = original_pitch.SectionProperties.Count To 1 Step -1
If pitch_segment.SectionProperties.Name(k) <> section_name Then pitch_segment.SectionProperties.Delete k, True
Next k
With pitch_segment
.SaveCopyAs _
FileName:=fso.BuildPath(.Path, original_pitch.SectionProperties.Name(i) & ".pptx"), _
FileFormat:=ppSaveAsOpenXMLPresentation
.Close
End With
Next i
MsgBox "Split completed successfully!"
End Sub
I could not get the above code to work.
However this is simpler and does work:
Sub SplitToSectionsByChen()
daname = ActivePresentation.Name
For i = 1 To ActivePresentation.SectionProperties.Count
For j = ActivePresentation.SectionProperties.Count To 1 Step -1
If i <> j Then ActivePresentation.SectionProperties.Delete j, True
Next j
ActivePresentation.SaveAs ActivePresentation.SectionProperties.Name(1)
ActivePresentation.Close
Presentations.Open (daname)
Next i
End Sub
I have edited fabios code a bit to look like this. And this works well for me in my PC
Option Explicit
Sub Split()
Dim original_File As Presentation
Dim File_Segment As Presentation
Dim File_name As String
Dim DupeName As String
Dim outputFname As String
Dim origName As String
Dim lIndex As Long
Dim K As Long
Dim pathSep As String
pathSep = ":"
#If Mac Then
pathSep = ":"
#Else
pathSep = "/"
#End If
Set original_File = ActivePresentation
DupeName = "TemporaryFile.pptx"
DupeName = original_File.Path & pathSep & DupeName
original_File.SaveCopyAs DupeName, ppSaveAsOpenXMLPresentation
origName = Left(original_File.Name, InStrRev(original_File.Name, ".") - 1)
For lIndex = 1 To original_File.SectionProperties.Count
If original_File.SectionProperties.SlidesCount(lIndex) > 0 Then
Set File_Segment = Presentations.Open(DupeName, msoTrue, , msoFalse)
File_name = File_Segment.SectionProperties.Name(lIndex)
For K = original_File.SectionProperties.Count To 1 Step -1
If File_Segment.SectionProperties.Name(K) <> File_name Then
Call File_Segment.SectionProperties.Delete(K, 1)
End If
Next K
outputFname = pathSep & origName & "_" & original_File.SectionProperties.Name(lIndex) & "_" & Format(Date, "YYYYMMDD")
With File_Segment
.SaveAs FileName:=.Path & outputFname & ".pptx", FileFormat:=ppSaveAsOpenXMLPresentation
.Close
End With
Set File_Segment = Nothing
End If
Next
Set original_File = Nothing
Kill DupeName
MsgBox "Split completed successfully!"
End Sub
This works for me (except for the filename):
Option Explicit
Sub ExportSlidesAsPresentations()
Dim oPres As Presentation
Dim sSlideOutputFolder As String
Set oPres = ActivePresentation
sSlideOutputFolder = oPres.Path & "\"
'Export all the slides in the presentation
Call oPres.PublishSlides(sSlideOutputFolder, True, True)
Set oPres = Nothing
End Sub

excel macro save sheets as csv with specific delimiter and enclosure

I am a total dummy as for vb and excel, have tried to combine 2 macros that I have found around here, into 1, but obviously did something terribly wrong and now i'm stuck.. First I just used this macro (saved it in as personal.xlsb so as to be able to use it in any workbook)
Sub CSVFile()
Dim SrcRg As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
ListSep = ";"
If Selection.Cells.Count > 1 Then
Set SrcRg = Selection
Else
Set SrcRg = ActiveSheet.UsedRange
End If
Open FName For Output As #1
For Each CurrRow In SrcRg.Rows
CurrTextStr = ìî
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & GetUTF8String(CurrCell.Value) & """" & ListSep
Next
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
Print #1, CurrTextStr
Next
Close #1
End Sub
That plus the GetUTF8String function code. Now that was working fine. Then I have thought well why not just experiment with my limited (that is a serious understatement) vb understanding, added the following code and changed the CSVFile sub into a function, which I then called from the sub below, with the output file name as a parameter (to be used instead FName = Application.GetSaveAsFilename). I thought yeah, this code saves all sheets automatically, now let's just make sure that the encoding and delimiter/enclosure setting function runs before each sheet is saved. It doesn't seem right but I thought hey why not try..
Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven
' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
' Save the file in current director
OutputPath = ThisWorkbook.Path
If OutputPath <> "" Then
Application.Calculation = xlCalculationManual
' save for each sheet
For Each Sheet In Sheets
OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"
' make a copy to create a new book with this sheet
' otherwise you will always only get the first sheet
Sheet.Copy
' this copy will now become active
CSVFile(OutputFile)
ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next
Application.Calculation = xlCalculationAutomatic
End If
Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Exit Sub
Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
"Source: " & Err.Source & " " & vbCrLf & _
"Number: " & Err.Number & " " & vbCrLf & _
"Description: " & Err.Description & " " & vbCrLf
GoTo Finally
End Sub
Saved that and with that I have managed to achieve something very different. On opening any workbooks, that macro runs and opens up my sheets from that particular workbook as csv files (without saving them). Now I am like Alice in Wonderland. How come it is running on file open? That is not desirable, so I went back to the macro code and changed it back to just the csvfile sub. Well that didn't help, no idea what I did there, was definitely editing the same macro... So I deleted the macro, the modul, I cannot imagine where the thing now is but it's still running + I get this warning that macros were deactivated. Can't get rid of it! Now lads, I'm sorry for the total lack of professionality from my side, this was just supposed to be a small favor for a client, without wasting loads of time learning vb, coz my boss doesn't like that... I am of course interested in how to achieve the goal of saving the sheets automatically after setting the deimiter and enclosure in them. And at this moment I am very interested in how to get rid of that macro and where it is hiding.. What have I done?! Thank you for your patience!
I think the problem lies with the line
OutputPath = ThisWorkbook.Path
Because you are running this from your personal.xlsb which is stored in your XLSTART folder it has created the CSV files in the same location. When Excel starts it will try and load any files that it finds in that location.
Just locate your XLSTART folder and delete any CSV files you find there.
Try using
OutputPath = ActiveWorkbook.Path
XLSTART folder location, dependent on your system, is probably something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\Excel\XLSTART