+ Reply to Thread
Results 1 to 3 of 3

Thread: Save if Directory Exists

  1. #1
    Registered User
    Join Date
    09-04-2009
    Location
    Portugal
    MS-Off Ver
    Excel 2003
    Posts
    23

    Save if Directory Exists

    Hi all,

    I wonder if its possible to have a code that saves a copy of the current workbook on exit if the following directory exists

    D:\Backup\

    If not it closes normally.


    Thanks in advance
    Last edited by phoztek; 07-04-2011 at 05:48 AM.

  2. #2
    Forum Guru Domski's Avatar
    Join Date
    12-14-2009
    MS-Off Ver
    What does it matter?
    Posts
    3,933

    Re: Save if Directory Exists

    Try this:

    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    If FileFolderExists("D:\Backup\") Then
        ThisWorkbook.SaveCopyAs "D:\Backup\" & ThisWorkbook.Name
    End If
    
    End Sub
    
    Public Function FileFolderExists(strFullPath As String) As Boolean
    'Author       : Ken Puls (www.excelguru.ca)
    'Macro Purpose: Check if a file or folder exists
    
        On Error GoTo EarlyExit
        If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
        
    EarlyExit:
        On Error GoTo 0
    
    End Function

    The code needs to go on the ThisWorkbook code page of your workbook's vba project.

    Dom
    "May the fleas of a thousand camels infest the crotch of the person who screws up your day and may their arms be too short to scratch..."

    Use code tags when posting your VBA code: [code] Your code here [/code]

    Remember, saying thanks only takes a second or two. Click the little star to give some Rep if you think an answer deserves it.

  3. #3
    Registered User
    Join Date
    09-04-2009
    Location
    Portugal
    MS-Off Ver
    Excel 2003
    Posts
    23

    Re: Save if Directory Exists

    Quote Originally Posted by Domski View Post
    Try this:

    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    If FileFolderExists("D:\Backup\") Then
        ThisWorkbook.SaveCopyAs "D:\Backup\" & ThisWorkbook.Name
    End If
    
    End Sub
    
    Public Function FileFolderExists(strFullPath As String) As Boolean
    'Author       : Ken Puls (www.excelguru.ca)
    'Macro Purpose: Check if a file or folder exists
    
        On Error GoTo EarlyExit
        If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
        
    EarlyExit:
        On Error GoTo 0
    
    End Function

    The code needs to go on the ThisWorkbook code page of your workbook's vba project.

    Dom
    Works like a charm,

    Thanks a lot

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0