3

我正在使用以下函数从工作簿中保存工作表并将其保存到单独的工作簿中。但是,它正在保存公式,而我宁愿只将值放在最终工作簿中。如何修改它,使生成的工作簿不包含公式而只包含值?

Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
    Dim wb As Workbook

    Set wb = Workbooks.Add(xlWBATWorksheet)
    With wb
        SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
        Application.DisplayAlerts = False
        .Worksheets(1).Delete
        Application.DisplayAlerts = True
        .SaveAs FilePath
        .Close False
    End With

End Sub

使用友情提供的链接我尝试了这个,但无济于事:

Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
    Dim wb As Workbook

    Set wb = Workbooks.Add(xlWBATWorksheet)
    With wb
        SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
        Application.DisplayAlerts = False
        .Worksheets(1).Delete
        .Worksheets(1).Copy
        .Worksheets(1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        Application.DisplayAlerts = True
        .SaveAs FilePath
        .Close False
    End With

End Sub

但我在 pastespecial 行收到错误??

4

3 回答 3

2
.Worksheets(1).Copy

这会复制工作表本身并且与PasteSpecial. 你可以使用:

.Worksheets(1).UsedRange.Copy

或类似的。例如,Worksheets(1).Cells.Copy

我认为应该是Worksheets(.Worksheets.Count)

在下文中,我SpecialCells仅用于识别工作表中的公式,并设置rng.Value = rng.Value将它们转换为公式的结果。

Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rngFormulas As Range, rng As Range

    Set wb = Workbooks.Add(xlWBATWorksheet)
    With wb
        SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
        Set ws = .Worksheets(.Worksheets.Count)
        Application.DisplayAlerts = False
        .Worksheets(1).Delete
        Application.DisplayAlerts = True

        With ws
            Set rngFormulas = ws.Cells.SpecialCells(xlCellTypeFormulas)
            For Each rng In rngFormulas
                rng.Value = rng.Value
            Next rng
        End With

        .SaveAs FilePath
        .Close False
    End With
End Sub

您将需要添加一些错误处理代码,以处理复制的工作表中没有公式的情况。(可能还需要考虑数组公式。)

于 2013-07-29T12:31:28.953 回答
2

复制值的最简单方法是分两步进行:
复制工作表,然后用它们的值替换公式

后:

.Worksheets(1).Delete

在您的原始代码中,添加以下行:

With Range(Worksheets(.Worksheets.Count).UsedRange.Address)
    .Value = .Value
End With

告诉 excel 用当前显示的.value=.value值替换每个值,因此所有公式都将替换为它们的计算值

于 2013-07-29T13:00:04.610 回答
1

对不起,答案开始看起来一团糟,所以删除它并重新开始。我已经写了这个 - 当我测试它时它似乎工作正常 - 你只需要一个额外的行来保存任何生成的电子表格。:)

For Each Cell In ActiveSheet.UsedRange.Cells
    Cell.Copy
    Cell.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Next
于 2013-07-29T11:07:28.273 回答