CheckIn Word document with VBA, without document closing and reopening - vba

Our company has recently migrated over to Sharepoint and we have been having untold amounts of fun forgetting to Check In and losing all our work.
So I've developed the following code which will be accessed by a button in the Quick access toolbar, cleverly disguised as a Save button.
I developed this by recording the action and tweaked with some help from the web.
Sub ChaveIn()
'
' CheckIn/Save = ChaveIn Macro
' Andrew Nathanson
' 2014/04/07
' Ver 1.0
'
'
If ActiveDocument.CanCheckin Then
TheCurrentfilename = ActiveDocument.FullName
ActiveDocument.CheckInWithVersion SaveChanges:=True, MakePublic:=False, _
Comments:="", VersionType:=wdCheckInMinorVersion
Documents.CheckOut FileName:=TheCurrentfilename
Documents.Open FileName:=TheCurrentfilename
Else
ActiveDocument.Save
End If
End Sub
My question is mostly aesthetic; If you Check In via Word's dialog box the document will pause, upload to the server, and let you carry on where you left off.
When my code does it the document shuts and opens again, losing your location in the document.
Is there a way to do it as Word does it?
Thank you.

Related

Word Save As Default and Iteration

I have tried many different ways of doing this but I can't find one that works for the application.
I have a MS Word Template that will be used by another team.
This is the criteria I have been given.
The initial file name must be 'PL' & the right most figures of a text control box. It should also say Issue 01.
The user must be able to chose the save location.
If the user then opens the document at a later date and saves it should retain the name and path.
If the user 'saves as' then it should up issue the Issue number.
The closest I can get to this working is this: -
In the top section I have this: -
Private WithEvents App As Word.Application and Dim n as long
Then in the Document New I have: -
Private Sub Document_New()
Set App = Word.Application
n = 0
End Sub
Then for the execution I have done this: -
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
ActiveDocument.SaveAs2 "PL" & Right(ActiveDocument.SelectContentControlsByTitle("Works Order Number").Item(1).Range.Text, 5) & " Issue " & Format(n, "00") & ".docx", wdFormatDocumentDefault
End Sub
However, this saves before the user has chosen a location. It works but the user needs to chose the location. So I tried this, this just does the same thing.
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
If Cancel = False Then
n = n + 1
ActiveDocument.SaveAs2 "PL" & Right(ActiveDocument.SelectContentControlsByTitle("Works Order Number").Item(1).Range.Text, 5) & " Issue " & Format(n, "00") & ".docx", wdFormatDocumentDefault
ElseIf Cancel = True Then
Exit Sub
End If
End Sub
Any suggestions or help would very much be welcomed. I basically just want to suggest the filename which up issues with every save as. But I cant find a way to influence that without physically saving.
Thank you in advance for your time and support.
You can repurpose ribbon controls (Save) to call your event handler first. Moreover, if required, you may cancel the default action in the event handler. See Temporarily Repurpose Commands on the Office Fluent Ribbon for more information. Repurposing ribbon controls give you a big plus - corresponding keyboard shortcuts are handled by your code as well. So, you will be able to intercept keyboard shortcuts by the same code.
In case of Backstage UI you can hide the SaveAs button and add your own. Read more about the Backstage UI in the following articles:
Introduction to the Office 2010 Backstage View for Developers
Customizing the Layout of Columns in the Office 2010 Backstage View
You really need to learn how to use the online documentation for VBA. If you had looked up DocumentBeforeSave you would have learned that Cancel is always False when the event is triggered. If you set it to True in the event handler it cancels the save.
You need to intercept the save before the dialog has been displayed, but the event is only triggered after the dialog. Because the criteria for Save is to use the standard functionality it is only the FileSaveAs you need to intercept.
Prior to the implementation of the Backstage view (the File tab) this could be solved simply by creating a routine named FileSaveAs. You can still do this and it will intercept the keyboard shortcut or clicking the QAT button. But it will not intercept the backstage commands. Only the event can do that without rebuilding the Backstage view, and the event won't work for you...
As far as intercepting the dialog to set the initial file name, that has been covered on SO before, here for example.

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.

Macro to save e-mail as text file, to be used in a rule

My problem is very similar to this thread and this one. I think my issue is to combine these two questions.
I am running:
OS: Windows 7 Enterprise Professional
Outlook 2010
VBA version 7.0
By reading these two questions as well as some other pages from Microsoft and elsewhere, I was able to open the VB editor and paste into it, this simple code:
Sub SaveEmail(msg As Outlook.MailItem)
' save as text
msg.SaveAs "C:\Users\mel\mailsave\email.txt" & Format(Now, "YYYYMMDDHHMMSS"), _
olTXT
End Sub
Is the "format" portion of my msg.SaveAs line, going to save a unique text file for each email matching my rule?
How do I run this macro to test and if successful, how do I run it repeatedly?
I tried going to the run menu and selecting run "sub/user form" item but the next dialog box is asking what to run and does not populate a list of macros available for running. Clicked on "save" icon but nothing changed.
Specifying a method with that signature (Sub method (var As Outlook.MailItem)) allows you to use the method when creating a mailbox rule. As far as I understand your question, you're beyond that point.
Question 1
The format portion of your code is only going to save a unique file at most once per second. You're appending the current date and time to the file. Your main problem, however, is not the timestamp, but the file format. You should apply the timestamp before the file extension, e.g.
msg.SaveAs "C:\Users\mel\mailsave\email" & Format(Now, "YYYYMMDDHHMMSS") & ".txt", olTXT
Question 2
If you add the macro to a rule, it will be run when the rule is matched. The macro can be tested by creating a method that grabs the currently selected mail, e.g.
Sub TestSaveEmail()
Call SaveEmail(ActiveExplorer.Selection(1))
End Sub
This macro can then be run by setting the cursor within the method and pressing F5.
The macro can also be added to the Outlook user interface by customizing the ribbon and adding a macro button. For help on customizing the ribbon, refer to the following article:
Customize the ribbon

Adobe "Save as" dialog boxes - MapPoint Excel VBA

I am trying to interact with an external Acrobat dialog window through VBA.
I am using MapPoint to generate maps and then save them as PDF files. Everything is controlled through VBA. I am using the "PrintOut" method of the maps to save them.
objApp.ActiveMap.PrintOut _
Title:=PDFTitle, _
PrintArea:=geoPrintFullPage, _
PrintQuality:=geoPrintQualityNormal, _
PrintOrientation:=geoPrintLandscape
Using this command in this way launches a "Save PDF file as" dialog box. At some point in the past we used to deal with this issue by using the SendKeys function to send {Enter} to the dialog and close it, but this no longer works.
I think the problem is that running this command causes VBA execution to stop until the dialog box is closed. Is there any way I could schedule a Sendkeys function to execute after the dialog opens? Or is there a way to prevent VBA execution from pausing?
Ideally, I would like to avoid having the dialog box in the first place, but that does not appear to be possible with my current setup. Specifying the OutputFileName when running the command does prevent the dialog from appearing, but it causes some kind of problem with the saved file (it can't be opened and appears to be corrupt).
Any suggestions are appreciated!
Can you download primopdf and try the following. PrimoPdf is a free print driver that allows you to save as PDF. http://download.cnet.com/PrimoPDF/3000-18497_4-10264577.html
Option Explicit
Sub PrintToPrimoPDF()
Dim strCurrentPrinter As String
strCurrentPrinter = Application.ActivePrinter ' save the currently active printer
On Error Resume Next ' ignore errors
Application.ActivePrinter = "PrimoPDF on Ne04:" ' change to PrimoPdf
Sheet1.PrintOut ' print the sheet1
Application.ActivePrinter = strCurrentPrinter ' change back to the original printer
On Error Goto 0 ' resume normal error handling
End Sub

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).