View Single Post
 
Old 02-05-2017, 05:05 AM
5kldqw 5kldqw is offline Windows XP Office 2010 32bit
Novice
 
Join Date: Feb 2017
Posts: 2
5kldqw is on a distinguished road
Default VBA Macro for opening and saving Word sessions

Hello everybody, after reading this forum and searching for myself I've decided to create a VBA macro for opening and restoring Word session that wouldn't close and save them in the process, because I couldn't find it anywhere else on the internet. Otherwise you can use an excellent gmayor add-in.

Here is a brief description of what the macro does:

  • it saves all currently opened word files path (a session) to a text file (except the unsaved files) into a specified folder
  • it opens the saved session specified by user (only files with unaltered path and name will be opened)
  • you can have as many sessions saved as you want and even change their name, delete them or specify the files in the session (using your favourite file manager and notepad)
Install instructions
  1. Add the VBA code (Macro) to the Word (e.g. using alt+f11). Please use other guides. Adding buttons is advised.
  2. Create a folder where sessions will be stored. Default folder path is "C:\vba". Suggested location of folder is in My Documents. Full path to the folder must then be entered in the code here (underlined part of the line): Set ts = fso.CreateTextFile("C:\vba\" & FileName, True)
  3. Verify that the Microsoft Scripting Runtime (scrrun.dll) is enabled in the references. Press alt+f11->tools menu->references and look for the Microsoft Scripting Runtime. Once found check if a checkbox next to it is checked. If not then check it and press OK.
  4. Test if the Macro works.
Use Instructions
  • Open a few saved files (not mandatory but suggested)
  • Run the SessionSave macro (e.g. by pressing the button you created or from the macros list)
  • That should have resulted in the file (session) being created in the specified folder (session is specified by current date and time). If saving was successful the window will popup (saying the saving was successful).
  • Close opened files (again not mandatory)
  • Run OpenSession macro.
  • Navigate to the folder you specified earlier with saved sessions.
  • Choose one file and click open.
  • The session should now be restored. You will be informed on the number of successfully and unsuccessfully opened files.
VBA Code (Macro)
Code:
Sub SessionSave()
' Created 04.02.2017
' Updated 05.02.2017
'
' Macro for word opened files session saving
'
' Microsoft scripting runtime (scrrun.dll) must be enabled in references
'
' This procedure saves current word session (opened windows) in a text file
' for later loading of the session.

' Declare variables
Dim Saved As Integer
Dim Unsaved As Integer
Dim fso As New FileSystemObject
'the file we're going to write to
Dim ts As TextStream
Dim FileName As String
Dim UnsavedName As String
    
    'open this file to write to it, where file name is composed of the current date and time
    'file with the same name will be overwritten
    FileName = Year(Now) & Format(Now, "mm") & Format(Now, "dd") & "_" & _
    Format(Now, "hh") & Format(Now, "nn") & Format(Now, "ss") & ".txt"
    Set ts = fso.CreateTextFile("C:\vba\" & FileName, True)
    
    'These two variable should say how many opened windows were saved and which remained unsaved
    'unsaved are those that are not saved on the disk yet
    Saved = 0
    Unsaved = 0
    
    'This cycle will loop through opened files and saves them into the file
     For Each adoc In Documents
    
     Debug.Print adoc.Path&; "\" & adoc.Name
        If adoc.Path <> "" Then
            ts.WriteLine (adoc.Path & "\" & adoc.Name)
            Saved = Saved + 1
        ElseIf adoc.Path = "" Then
            Unsaved = Unsaved + 1
            UnsavedName = UnsavedName + adoc.Name + ","
        Else
            Debug.Print ("Error saving file path")
        End If
     Debug.Print adoc.Path&; "\" & adoc.Name
    
    Next adoc
    
    'closes the file
    ts.Close
    
    'informs user on the result of the procedure
    MsgBox "Saving of the session" & FileName & " was successful. There are " & _
            Saved & " files recorded. Unrecorded files number is " & Unsaved & "(" & UnsavedName & ")." _
            , vbInformation, "Session save result"
End Sub

Sub OpenSession()
' Created 04.02.2017
' Updated 05.02.2017
'
' Open saved session of word files Macro
'
' Microsoft scripting runtime (scrrun.dll) must be enabled in references
'
' This procedure opens saved sessions (opened windows) from text files
' created by the SessionSave procedure.
'
Dim fso As New FileSystemObject
'the file we're going to read from
Dim ts As TextStream
Dim FilePath As String
Dim ThisLine As String
Dim i As Integer
Dim FilesNotFound As String

'only allow the user to select one file
'make the file dialog visible to the user
With Application.FileDialog(msoFileDialogOpen)
    .AllowMultiSelect = False
    .Show

    If (.SelectedItems.Count = 0) Then
        Exit Sub
        '// dialog dismissed with no selection
    Else
        FilePath = .SelectedItems(1)
    End If
End With

'... we can open a text file
Set ts = fso.OpenTextFile(FilePath, ForReading)

'keep reading in lines till no more
    FilesNotFound = ""
    i = 0
    Do Until ts.AtEndOfStream
        ThisLine = ts.ReadLine
        i = i + 1
        'Debug.Print "Line " & i, ThisLine
        If (Dir(ThisLine) > "") Then 'check if the file exists
            Documents.Open FileName:=ThisLine
        Else 'if it doesn't exist then save the filename
            FilesNotFound = FilesNotFound + ThisLine + ", "
        End If
    Loop

'close down the file
ts.Close

'Tell the user if the opening of the session was successful; if not then tell, which files couldn't be opened
If FilesNotFound = "" Then
    MsgBox "Session " & FilePath & ": All the files were opened.", vbInformation
Else
    MsgBox "Session " & FilePath & ": Those files could not be opened (path not found): " _
    & FilesNotFound, vbExclamation
End If

End Sub
Feel free to alter the code as you wish, just please post your updates to this forum. Please also post here if you had any trouble installing or running the macro. The Macro has been tested on WinXP and Word 2010 (both 32bit).
5kldqw

Last edited by 5kldqw; 02-05-2017 at 11:03 AM.
Reply With Quote