+ Reply to Thread
Results 1 to 2 of 2

Macro to close all open workbooks save two not working

Hybrid View

  1. #1
    Registered User
    Join Date
    09-23-2011
    Location
    Calcutta
    MS-Off Ver
    Excel 2007
    Posts
    26

    Macro to close all open workbooks save two not working

    Hi,

    I need a macro to close all open workbooks except two of them, named say ab_cd_de.xlsm and fg_hi_jk.xlsx. (using these weird formats because the actual file names are similar (long names with many underscores).

    The macro is located in the ab_cd_de file.

    I am using the following macro:

    For Each Workbook In Application.Workbooks
    
          If Workbook.Name <> "ab_cd_de.xlsm" And Workbook.Name <> "fg_hi_jk.xlsx" Then
                 Workbook.Activate
                 Workbook.Close (False)
          End If
    
    Next Workbook
    I have also tried using the following code:

    For Each Workbook In Application.Workbooks
          If Not (LCase(workbook.Name) Like "ab_cd_*" Or LCase(workbook.Name) Like "fg_hi_*") Then
                      Workbook.Activate
                      Workbook.Close (False)
          End If
    Next workbook
    Both of the codes above fail to retain the two excluded files above and close one of them as well.
    In effect I am left with only the fg_hi file for the first stretch of code and the ab_cs file for the second stretch.

    Is there any way that I can ensure both of the files remain open after the operation?

  2. #2
    Forum Contributor Dave H9's Avatar
    Join Date
    03-10-2011
    Location
    Manchester, England
    MS-Off Ver
    Excel 2007
    Posts
    418

    Re: Macro to close all open workbooks save two not working

    You could try leaving the TRUE condition blank and performing your function on FALSE -

    For Each Workbook In Application.Workbooks
    
          If Workbook.Name = "ab_cd_de.xlsm" or Workbook.Name = "fg_hi_jk.xlsx" Then
          
          Else
                 Workbook.Activate
                 Workbook.Close (False)
          End If
    
    Next Workbook
    Dave H9

+ 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.6.0 RC 1