VBA:自动保存并关闭除Macro工作簿之外的所有当前工作簿

时间:2014-06-11 18:05:15

标签: excel vba excel-vba

我正在尝试关闭除了我的宏工作簿之外的所有当前打开的工作簿,并且.Save作为我的路径,但我希望我的路径是我的宏工作簿[D1]中的指定单元格。我还希望将文件名保存为我正在保存和关闭的工作簿中的单元格A1。现在我被卡住了。我已经列出了我目前正在使用的代码,而我正在使用这段代码遇到的问题是它保存为当前所选工作簿中单元格A1中的名称与代码当前循环使用的工作簿。我希望这是有道理的。

            Option Explicit
            Public ThisFile As String
            Public Path As String

            Sub CloseAndSaveOpenWorkbooks()
                Dim Wkb As Workbook
                ' ThisFile = ActiveWorkbook.Sheets(1).Range("A1").Value ** Commented out as this piece of code was not working as intended **
                Path = "C:\Users\uuis\Desktop"

                With Application
                    .ScreenUpdating = False

                     '       Loop through the workbooks collection
                    For Each Wkb In Workbooks

                        With Wkb

                            If .Name <> ThisWorkbook.Name Then
                             '               if the book is read-only
                             '               don't save but close
                            If Not Wkb.ReadOnly Then

                                .SaveAs Filename:=(Path & "\" & ActiveWorkbook.Sheets(1).Range("A1").Value & ".xls"), FileFormat:=xlExcel8

                            End If

                             '               We save this workbook, but we don't close it
                             '               because we will quit Excel at the end,
                             '               Closing here leaves the app running, but no books

                                .Close

                            End If

                        End With

                    Next Wkb


                    .ScreenUpdating = True
                    ' .Quit 'Quit Excel
                End With
            End Sub

1 个答案:

答案 0 :(得分:0)

ActiveWorkbook.Sheets(1).Range("A1").Value

应该是

Wkb.Sheets(1).Range("A1").Value