How to change default path in save on close prompt? - vba

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.

Related

Disable Save As but not Save in Word 2010

I am looking to disable Save As in a Word 2010 file but still allow save. In other words I want users to be able to update the existing file but not create copies. I realize that this is impossible to truly do for people who know workarounds but for the general user I have successfully done this in Excel but am pretty new to word VBA.
When I add the following to a brand new document everything works as intended:
Sub FileSaveAs()
MsgBox "Copies of this file cannot be created. Please save changes in the original document." & _
, , "Copy Cannot be Created"
End Sub
My document has other macros for various command buttons but none of them involve saving the document (under original name or save as). There is also a macro running on open but that is 1 line going to a bookmark. When I try to "save as" in this document I get the message box as intended. When I try to "save" though things get strange: I get the save as dialogue (problem 1). Whether I try to save either under same name or other name the dialogue behaves as it normally would except it doesn't save and the dialogue box opens again automatically essentially creating an endless loop until I hit cancel (problem 2). I also intermittently get a "disk is full" warning pop-up after trying to save which I can dismiss but appears a few minutes later as long as he file is open (perhaps related to autosave?)
Since the macro works in the test file I assumed this strange behavior must be something elsewhere in my code but my document with the other macros saves normally as long as I don't include the save as code above so now I'm totally confused. Before I put up the rest of my code which is lengthy and for the reasons stated above I would not think impact things, I figured I'd ask this:
1. Is there any place other than my other command button macros that could be causing this behavior?
2. Is there a better method people recommend to achieve my ultimate goal of disabling save as but not save?
Thanks in advance for any advice you can provide.
The Word application has a DocumentBeforeSave event. To enable application events I suggest to create a class module by the name of ThisApplication and paste the following code into it.
Option Explicit
Private WithEvents App As Application
Private Sub Class_Initialize()
Set App = Word.Application
End Sub
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, _
SaveAsUI As Boolean, _
Cancel As Boolean)
If SaveAsUI Then
MsgBox "Please always use the ""Save"" command" & vbCr & _
"to save this file.", _
vbExclamation, "SaveAs is not allowed"
Cancel = True
End If
End Sub
Add the following code to your ThisDocument module.
Dim WdApp As ThisApplication
Private Sub Document_Open()
Set WdApp = New ThisApplication
End Sub
You may add the Set App = ... line to your existing Document_Open procedure. After the WdApp variable has been initialised all application events will be received by the ThisApplication class where the DocumentBeforeSave event procedure is programmed not to allow SaveAs.
Of course, this is a blanket refusal for all documents. Therefore you may wish to add code to the procedure to limit the restriction to certain documents only. The proc receives the entire document object with all its properties, including Name, Path, FullName and built-in as well as custom properties. You can identify the files you wish to be affected by any of these.
Note that the WdApp variable will be erased in case of a program crash. If this happens the application events will no longer fire. It may be useful to know that application events occur before document events. This is if you wish to use the application's DocumentOpen event as well as or instead of the document's Document_Open event.

vba Excel - How to Check if a SharePoint Website File is Open

I've searched the internet for the answer to this and keep running into issues getting it to work.
I need to check if a file at the below location is open/locked, and then have the code wait 15 seconds and then try again. Right now if someone else has the file open a dialog box opens asking if I want to open read only, which I don't want. I tried using Application.DisplayAlerts = False to get the message not to appear but that didn't seem to work. So I have two main issues:
Checking if the file is open and waiting to try again.
Stop the dialog box from opening asking to open as read only.
Workbooks.Open filename:= _
"https://somecorporatewebsite/sites/TNKYWest/Engr/ASE%20Updates/Shared%20Documents/ASENW Updater.xlsx"
Try something like this:
From MSDN site:
https://msdn.microsoft.com/en-us/library/office/ff193284.aspx
Sub UseCanCheckOut(docCheckOut As String)
Dim docCheckout
set docCheckout="File name to open"
' Determine if workbook can be checked out.
If Workbooks.CanCheckOut(Filename:=docCheckOut) = True Then
Workbooks.CheckOut (Filename:=docCheckOut)
Else
Found at the MSDN Website:
https://msdn.microsoft.com/en-us/library/office/ff822851.aspx
Application.Wait(Now + TimeValue("0:00:10"))
Workbooks.CheckOut (Filename:=docCheckOut) 'Try to check the file out again.
End If
End Sub
This part is covered in the
IF workbooks.cancheckout(filename:=docCheckout)=true then workbooks.checkout ' method in part 1.

Use VBA to retrieve and call VBA code from a text file

I am working on a project to process some incoming Outlook messages using rule-triggered VBA code.
However, I don't want to have to manually update the code for each user's inbox any time the code needs to change. So my idea is to put a text file on a shared drive and have the VBA pull that text file down and treat it like code. Essentially, I want to use that text file like a little code library.
I was able to find this link that has gotten me very close to my goal. However, I'm having a few issues with it.
Here is the code I put together. It is attached to the click event of a Rectangle shape I inserted into an Excel file. Eventually, I'll move this over to Outlook, but I'm just doing a basic test with Excel VBA first.
Sub Rectangle1_Click()
On Error GoTo Err_Handler
Dim enviro As String
Dim myFile As String
'Pull code "library" from text file on user's desktop
'This will eventually be changed to reside on a shared drive
enviro = CStr(Environ("USERPROFILE"))
myFile = enviro & "\Desktop\hello_vba.txt"
'If the "Library" module already exists, delete it
For Each a In Modules
If a.Name = "Library" Then
a.Delete
Exit For
End If
Next
'Add a new module
Set m = Application.Modules.Add
'Rename it to "Library"
m.Name = "Library"
'Insert the text from the other file to this new module
m.InsertFile myFile
'Call the hello() subroutine from the retrieved text file
Library.Hello
Exit_Here:
'Cleanup code goes here
Exit Sub
Err_Handler:
MsgBox Err.Description
Resume Exit_Here
Exit Sub
And here is the content of the external text file named "hello_vba.txt":
Sub Hello()
MsgBox "Hello"
End Sub
The first time I run this, using the debugger I can see that it creates the new module and then gets to the line that says:
m.Name = "Library"
And then a window pops up in the debugger that says:
Can't enter break mode at this time
When I click continue on that message, I get an
Object Required
error message. If it run it again, then I get some more error messages but I do eventually get a successful "Hello" message box pop up.
I'm wondering if I may not have "Dim"ed the "a" or "m" variables properly or if there is a problem trying to pull in a text file and immediately treat it like code?
Any ideas?
To run your new code, try using Application.Run instead of Library.Hello
It would be written:
Application.Run("Hello")
Does that work?

Word macros not running correctly when opened from PowerPoint action button

I have a Word template (suggestion from) which includes an autonew macro to insert a reference number at a book mark and an action button (Submit)which saves the resulting document with the reference number as part of the file name and closes Word. This works perfectly well when opening the template via Windows Explorer.
We also have a PowerPoint show with action settings hyperlinking to various documents. The link will open the above template OK but does not insert the reference number. Also when the 'submit' button is hit, the file saves as another template with the reference number included.
I am not sure if the issue is Word or PowerPoint-related. The code for the Word template is
Sub AutoNew()
REF = System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", _
"MacroSettings", "REF")
If REF = "" Then
REF = 1
Else
REF = REF + 1
End If
System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", "MacroSettings", _
"REF") = REF
ActiveDocument.Bookmarks("REF").Range.InsertBefore Format(REF, "000#")
End Sub
Private Sub CommandButton1_Click()
REF = System.PrivateProfileString("L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Settings.Txt", _
"MacroSettings", "REF")
ActiveDocument.SaveAs FileName:="L:\Local\Lab\Section - Support Services\Health and Safety\H&S Suggestions\Suggestion " & Format(REF, "000#.doc")
Application.Quit
End Sub
Any help or pointers would be appreciated as if it works I'd like to use for various other templates.
From the description, it's kind of hard to get an accurate idea of what's happening, but it SOUNDS like the the AUTONEW just might not get run in that particular combination.
You could verify this by using some logging or MSGBOX calls to see exactly what macros are being run, when.
Check the docs on Autonew here
http://support.microsoft.com/kb/211659
Sounds like it won't run if the macro is saved in Normal, which doesn't sound like the case here but it's worth noting.
You might also consider using the AutoOpen macro and checking other elements to make sure this is a brand new doc instead of one that's already been saved (like checking the content of the Document.Fullname property).

Leaving a Project file open after retrieving it with GetObject

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