Release a file from excel generated by VBA to allow for moving of file - vba

I am using some code in my excel document to open images, rotate them as appropriate and then save them to a temp folder (see How do I rotate a saved image with VBA?).
I am now trying to rename these generated images within the same folder using Name... as..., however this throws up an error, saying that the image is still in use by Excel ("File/Path access error" in VBA - it tells me its in use by excel when renaming it in an explorer window though)
Is there any way to "throw this out" of Excel using VBA before this stage? I did try Set p = Nothing (with p coming from Set p = .Pictures.Insert(Filepath)) but this still gives an error. The sheet that the new image is created from is deleted after it is saved to the temp folder so it does not exist on the sheet any more either. Once I fully close excel, I can rename the file again.

The "solution" I ended up with was to copy folder C:\Temp\a\ to C:\Temp\b\ and make the changes from there before copying to \\my\actual\location
This works OK as a decent workaround for this instance, but by no means a 100% complete answer to the question

YOUR CODE HERE.....
CLOSE
'by add "close" at the ending of your line before conducting the next action

Related

PowerPoint 2013 macro keeps file locked open after close command

I have a PowerPoint VBA function that opens presentations, copies slides into the active presentation, then closes the source presentation. It worked fine in 2010, but fails in 2013 (all on Windows 7) if it tries to open the same presentation more than once. It appears to me that after the presentation.close command is issued, the window is closed, but the file remains locked open until the VBA code exits. So if the code attempts to open that file again it returns the error:
"Method 'Open' of object 'Presentations' failed"
Here's a simplified form of the function I'm running that behaves the same way. I've had a colleague test this again in PowerPoint 2010 and it runs fine. I've also had a colleague test it under his 2013 to make sure it's not something with my particular installation.
Sub testopen()
Dim ppFile As Presentation
Dim i As Integer
Const fpath = "C:\test.pptx"
For i = 1 To 2
Set ppFile = Application.Presentations.Open(fpath)
ppFile.Close
Set ppFile = Nothing
Next i
End Sub
The file test.pptx is just a blank presentation. In debug mode I can see the file opens and closes on the first loop, then on the second loop the open command fails and I can see in Windows explorer that the hidden temporary file still exists, indicating the file is still open, until I exit the VBA code. I also verified that the file is held open by adding in a function to check the file open status.
I've spent probably an hour googling this and cannot find any other descriptions of this problem. I'm sure I can implement a workaround but it's driving me crazy that I can't find any other reports of seemingly such a simple issue. Any suggestions are greatly appreciated! Thanks.
The Best way that I have achieved this is to simply create a VBS file and in the VBS file I call out the desired VBA code. It's little more hassle than to write the VBA code, but it's the solution that worked for me.
For example in the VBS file:
Dim args, objPP
Set args = WScript.Arguments
Set objPP = CreateObject("Powerpoint.Application")
objPP.Open "C:\path\to\file.ppx"
objPP.Visible = True
objPP.Run "The_Macro"
objPP.Save
objPP.Close(0)
objPP.Quit
Or better yet, have the entire code within the VBS file and have it copy the desired slides.
Hope this helps you achieve your result.
Setting the file as Read Only resolved the issue. The open command is now:
Set ppFile = Application.Presentations.Open(fpath, msoTrue)
Also, saving the file before closing it resolved the issue. For that, add:
ppFile.Save
Interestingly, I had already tried setting the Saved property to True (ppFile.Saved = msoTrue), which does NOT work. Thanks to Michael for his suggestion on the VBS script. That does work and I had never run an external VBS script so I learned something new. In this case, I'd prefer to stick with a VBA solution.

When is an extension required in workbook name? [duplicate]

This question already has an answer here:
Excel VBA requiring file extension for workbook reference in some systems
(1 answer)
Closed 3 years ago.
I have a directory of excel files that interact with each other through VBA code in a master file.
I've never had a problem with this before, but after copying the whole directory to do some development work on the copy (keeping the original intact in a different location) I'm running into a "subscript out of range" problem when referencing the workbook.
For example, everything ran fine previously with this line of code (nothing in the actual code has been changed):
Code that now throws an error (never used to):
ScheduleLocation = Workbooks("Master Schedule").Path
However, this line now throws an error. If I replace "Master Schedule" with "Master Schedule.xlsm" everything works again. I've had this problem before, but I've never been able to put a finger on the root cause of the problem.
Code that doesn't throw an error:
ScheduleLocation = Workbooks("Master Schedule.xlsm").Path
Hence my question: why is this? Why would the name (without extension) be insufficient sometimes, and sometimes not?
Have you got "Show file extension of known file types" turned on in windows explorer?
Try to run the code with hidden and visible extensions.
It is good practice to assign the workbook to variable on open.
Dim wbInput as Workbook
Set wbInput = Workbooks.open ("C:\Master Schedule.xslx")
Now you can work on variable without caring about the system settings for extensions.

VBA Word 2010 Paste Error / No Wait Command

I have a project that takes several documents as inputs, does some processing on them, and creates several new documents at the end. I am currently running into problems with pasting content from one Word document into another. The following code snippet seemed relevant:
Set refOrigin = FindReference(OriginDoc)
Set refDest = PasteDoc.Range(PasteDoc.Content.Start, PasteDoc.Content.End)
refDest.Collapse wdCollapseEnd
refOrigin.Copy
refDest.Paste
When running this code, I will occasionally get Run-time error 4198, Command Failed at the paste line in the code. However, when I go into the debugger, I can see that both refDest and refOrigin are valid ranges. Furthermore, when I step through the code line-by-line, it works. However, I can tell that in the instance where it failed, it inserted an embedded Word document already.
I've done some research on the issues and I believe that there is some type of problem of the code running to fast for the clipboard to keep up with it sometimes. This makes sense to me because when I run the macro from a document on a network drive, it runs without a hitch.
I thought that I would be able to simply add a wait command with Application.Wait, but it turns out that Word 2010 doesn't support this command; it's only in Excel.
Does anyone have ideas as to the root of this problem, possible solutions, or any way to give Word 2010 a wait command? Thanks.
For completeness, the following code mimics the Excel `Application.Wait' method from this question.
Dim tmpStart
tmpStart = Timer
Do
DoEvents
Loop While (tmpStart + 1) > Timer

Batch add a macro to word documents?

I have several hundred .doc word documents to which I need to add a macro which runs when the .doc file is opened and creates a header for said document based on the file name. Is there a way to do this as a batch? I have been individually opening each document and going into visual basic --> Project --> This Document then inserting a .txt file which contains the code. Is there a fast way to do this for multiple documents?
As a learning exercise, put this into the "ThisDocument" part of Normal (the Normal.dot template) in the VBE
Open a word document and watch what happens.
I don't think you need to put your code in every single file, I think you should be OK with using the Document_Open event in Normal.dot.
Just make sure it shows up as a reference in your word documents that you open but I don't see why it wouldn't
If you absolutely need it in every file then it can be done but the problem is if you make one small change to the code, you have to go through all this again. The idea with code is to write it once, use it many times.
You can write VBA code that alters the VBA code in other documents, but you need to "Trust access to the VBA project object model" in the Trust Centre options. This could open you up to viral code if you download Word documents with malicious VBA code in them. What you want to do, essentially, is write a VBA virus. There are legitimate reasons for doing this, and also malicious ones, I leave the ethics of the uses of these techniques up to the user. Knowledge itself is not malicious.
Here's the meat, you will need to write your own code to loop through the documents and possibly save them as .docm files.
Sub ReplaceCode()
Set oDoc = ActiveDocument
Set oComponents = oDoc.VBProject.VBComponents
For i = oComponents.Count To 1 Step -1
If oComponents(i).Type = 100 And oComponents(i).Name = "ThisDocument" Then
With oComponents(i).CodeModule
.DeleteLines 1, .CountOfLines
.AddFromFile "C:\ThisDocument.cls"
End With
End If
Next i
End Sub
Also, if you create your code file by exporting from VBA, you will need to remove this from the top of the .cls file:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Personally, I would drive this from Excel, maybe using a worksheet to hold a list of the files or locations to update, and another sheet for the code to populate with a list of files updated.

Sparkline Printing to PDF

I have an issue where when I export to PDF via VBA my sparkline graphs are not printed. I've browsed your site, and a few others, trying to come up with a solution. Unfortunately I can't get it to work.
I'm the only one that uses the application, so the process is completely visible. I've tried to do all of the following before the export line in an effort to get the sparklines to 'refresh':
application.screenupdating = false then application.screenupdating = true
application.visible = true (based on forum here, even though it was never hidden)
select the cell where sparkline is located
select entire sheet where sparkline(s) are located
select.copy the cell where sparkline is located
application.wait to see if it would refresh
application.calculate to see if it would refresh
I really can't think of anything else to try. The spreadsheet is designed to create a report for a single entity, print the report, and then move on to create the next report for a different entity (pulls data from Access, creates over 200 10 page reports).
Any help is appreciated.
Thanks - Kris.
I had the same issue and I tried all of your listed ideas as well as DoEvents, but after testing the code line for line I found the offending code was:
.Axes.Vertical.MinScaleType = xlSparkScaleGroup
For some reason the xlSparkScaleGroup interferred with the update of the sparklines on the page and when I tried to update-print-update-print--- the sheet the sparklines were missing. My solution was to simply remove this code and then manually set the scales. Something like this:
.Axes.Vertical.MinScaleType = xlSparkScaleCustom
.Axes.Vertical.CustomMinScaleValue = Application.WorksheetFunction.Min(Range(SLAddress))
.Axes.Vertical.MaxScaleType = xlSparkScaleCustom
.Axes.Vertical.CustomMaxScaleValue = Application.WorksheetFunction.Max(Range(SLAddress))
where SLAddress was the address of the sparkline data I was using. I hope this helps solve your issue and maybe Microsoft will actually fix this issue.
Had to use a temp file to make it happen. Basically saved the current file as a temp file using 'savecopyas', then open the temp file (which allowed it to refresh the sparklines) do the print, close the temp file, and then start the process over again.
Hope they fix this at some point.
Kris.