保存工作簿的副本时,工作表将被取消隐藏

时间:2018-01-10 23:35:28

标签: excel vba excel-vba

我将工作簿的副本保存为非宏启用的工作簿,其中隐藏了一些后端工作表。我更喜欢将后端工作表保留在工作簿中以备记录。

工作簿中的第一个工作表是隐藏工作表之一,此处命名为“Sheet1”。出于某种原因,当我打开新保存的工作簿的副本时,它不再被隐藏。如果我在保存和关闭之间添加断点,我甚至可以看到它在VBA保存后被正确隐藏。

任何有关解决此问题的帮助表示赞赏!

Sub MyVBA()

        Dim ws As Worksheet
        Dim wsName As Variant

        'The string in quotes is what name the report should save and email as.
        wsName = "My Workbook - "

            ActiveWorkbook.Save

            'Saves a master copy
            'Name the first and last of the backend sheets you want to hide before saving a master. It will hide everything in between.
                For i = Sheets("Sheet1").Index To Sheets("Sheet5").Index
                    Sheets(i).Select Replace:=False
                Next i
                ActiveWindow.SelectedSheets.Visible = False

            ThisWorkbook.Sheets.Copy
            With ActiveWorkbook
                .SaveAs ThisWorkbook.Path & "\" & wsName & Format(Date, "yyyy-mm-dd") & ".xlsx", FileFormat:=51
                .Close
            End With

    End Sub

编辑:

我用明确的引用测试了它,我遇到了同样的问题。

            For i = Sheets("Data").Index To Sheets("Key").Index
                Sheets(i).Select Replace:=False
            Next i
            Workbooks("Test.xlsm").Windows(1).SelectedSheets.Visible = False

        Workbooks("Test.xlsm").Sheets.Copy
        With ActiveWorkbook
            .SaveAs Workbooks("Test.xlsm").Path & "\" & wsName & Format(Date, "yyyy-mm-dd") & ".xlsx", FileFormat:=51
            .Close
        End With

1 个答案:

答案 0 :(得分:2)

发生这种情况的原因是您的sheets.copy选择隐藏表单1。我复制了您的代码,以便在复制工作表后激活工作簿中的最后一个工作表#。

Sub MyVBA()

    Dim ws As Worksheet, i As Long
    Dim wsName As Variant

    'The string in quotes is what name the report should save and email as.
    wsName = "My Workbook - "

    ActiveWorkbook.Save

    'Saves a master copy
    'Name the first and last of the backend sheets you want to hide before saving a master. It will hide everything in between.

    Dim LastSht As Long
    LastSht = ThisWorkbook.Sheets.Count

    For i = Sheets("Sheet1").Index To Sheets("Sheet5").Index
        Sheets(i).Select Replace:=False
    Next i
    ActiveWindow.SelectedSheets.Visible = False

    ThisWorkbook.Sheets.Copy
    Sheets(LastSht).Activate
    With ActiveWorkbook
        .SaveAs ThisWorkbook.path & "\" & wsName & Format(Date, "yyyy-mm-dd") & ".xlsx", FileFormat:=51
        .Close
    End With

End Sub