Leaving a Project file open after retrieving it with GetObject - vba

What is the right way to leave an MS Project file opened with GetObject() open and visible to the user after the end of a macro in a different app?
The information I found online suggests that setting the Application.UserControl property to True before the objects go out of scope should allow the user to continue using the opened file. However, for MS Project at least, the Application.UserControl property appears to be read-only. Is there a way to work around this?
A simplified example showing the problem:
Sub AddTasks()
Dim proj As Object
' Already have the file path from another part of the workflow
Set proj = GetObject("C:\projtest.mpp")
' perform some calculations and add new tasks to project
proj.Tasks.Add "additional task"
' Leave Project open and visible for the user
proj.Application.Visible = True
proj.Application.UserControl = True ' Gives "Type Mismatch" error
' without the UserControl line, runs ok, but Project closes after the end of the macro
End Sub

Instead of using GetObject, could you create an instance of the application and open the project file in the instance?
Sub AddTasks()
Dim msProj as Object
Set msProj = CreateObject("Project.Application")
msProj.FileOpen "C:\projtest.mpp"
'do stuff to project file here
msProj.Visible = True
End Sub
Something like the above (I can't test the above code because I don't have MSProject, but similar code works for MSWord)

For Project UserControl just indicates if the user started the application or not; it appears to be read-only because it is. I've not done what you're asking for with Project, although here is a similar example for Word trying to see and find running instances of Excel. Perhaps this helps a little:
can-vba-reach-across-instances-of-excel

Related

How to change default path in save on close prompt?

I'm trying to create a template that automatically changes folder suggested by the save prompt to a specified location. I've managed to get it partially working using the following code (modified from here):
Sub FileSave()
Dim UserSaveDialog As Dialog
Set UserSaveDialog = Dialogs(wdDialogFileSaveAs)
'save changes if doc has been saved previously
If ActiveDocument.Path <> "" Then
ActiveDocument.Save
Exit Sub
End If
With UserSaveDialog
.Name = "C:\Users\david\Downloads"
If .Display Then
UserSaveDialog.Execute
End If
End With
End Sub
Using this code, my macro correctly intercepts the default save behaviour (or Ctrl+S), however it doesn't intercept the save dialog when closing the file. I've tried basically copying this code to a new Sub called Document_BeforeSave, FileExit, FileCloseEx and FileCloseAllEx (yes, I am having difficulty with all the different objects and what they do :) all to no avail.
I'm not sure the same code will even work in this event, but I don't even get any indication that it has failed to work, so it seems I'm using the wrong event.
Turns out I somehow missed AutoClose (MS Docs), which does what I want.

Close MS Project using VSTO

I have a VSTO on MS Project. I use VB.NET. What I need is when I press the button I created on the ribbon, it will perform some codes which will update the info of some task, however, I would need to close the MS Project automatically. I tried application.FileCloseEx(), but it only closes the file, the MS Project is still loaded. I need similar to clicking the x button of the window.
Thanks,
Gilbert
If your MS Project application object is represented by "appMSProject" then it's as simple as:
appMSProject.Quit
OR say in a macro running under Project:
Application.Quit
Here's how I do it in VBA from Excel or Access. As far as I can tell the objects & methods are the same in VB.NET. Bottom line is that I create an instance of the MS Project object which starts the app & opens a file, execute some work, close the file, then destroy the MS Project object by setting it to Nothing. That has the effect of closing the app. You can also use "appMSProject.Quit" followed by setting it to Nothing. Frankly the 2nd option looks more orderly & easier to understand in code. Anyway, here's a sample of the way I do it:
Dim appMSProject As MSProject.Application
Dim prjPrj As MSProject.Project
Dim strPrjFile As String
strPrjFile = "C:\where_is_my_file\file_name.mpp"
Set appMSProject = New MSProject.Application
appMSProject.FileOpenEx Name:=strPrjFile
Set prjPrj = appMSProject.ActiveProject
'''Do something in here with the prjPrj
'Close the file, in my case w/o saving
appMSProject.FileCloseEx pjDoNotSave
'Destroy the objects
Set prjPrj = Nothing
Set appMSProject = Nothing
FYI - In this example I'm doing background work so I don't show the app. I also use "early binding".
Here's an MSDN example that does show the app with more info on early -vs- late binding - https://msdn.microsoft.com/en-us/library/office/ff865152.aspx

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.

Access to path is denied when trying to import from the client's desktop with SSIS

I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.

Saving Template after VBA references are added

I have some code which adds the VBA references i require for using Access. (it checks if the user already has them included).
This all works fine. My problem is when i then go to close word I am prompted to save the Acronym Tools template (Where the macro that this code is stored). Is it possible to do this programtically so that is it done as soon as references are added and the user does not see it happening?
The code i use:
If Not isReferenceLoaded("Access") Then
MsgBox ("Access Object library not found, the script will now attempt to find the library for you.")
'Ensure access library is included so database actions can be done
ID.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\MSACC.OLB"
MsgBox ("Access Object library added")
End If
If Not isReferenceLoaded("DAO") Then
MsgBox ("DAO library not found, the script will now attempt to find the library for you.")
'Ensure access library is included so database actions can be done
ID.AddFromFile "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE14\ACEDAO.DLL"
MsgBox ("DAO library added")
End If
The function to see if reference is loaded:
Private Function isReferenceLoaded(referenceName As String) As Boolean
Dim xRef As Variant
For Each xRef In ThisDocument.VBProject.References
isReferenceLoaded = (xRef.Name = referenceName) Or isReferenceLoaded
Next xRef
End Function
If you don't want to save the document with the updated references (they'll be remade next time the doc is open, I guess) add to your Document object (supposedly named ThisDocument) the following subroutine:
Private Sub Document_Close()
ThisDocument.Saved = True
End Sub
This would inhibit the save-check only for ThisDocument. Add a Call ThisDocument.Save statement at the beginning, if you do want to save. However, I would count on the users to save their changes... but that's a matter of strategy, please do as you wish.
Nota Bene: Do not forget to save after adding the function: you'll lose the changes if you forget to; Word will ignore your changes because it was just instructed to do so by the function. :-)