复制所有值VBA脚本失败

时间:2014-10-27 11:54:54

标签: vba excel-vba excel

我正在尝试创建一个VBA脚本,将整个工作簿中的所有数据复制为值作为粘贴,然后另存为新工作簿,从而删除所有公式。

这是我的代码:

Sub MakeAllVals()
Dim wSheet As Worksheet

For Each wSheet In Worksheets
    With wSheet
        .UsedRange.Copy
        .PasteSpecial xlValues
    End With
Next wSheet

Application.Dialogs(xlDialogSaveAs).Show
End Sub

我在.PasteSpecial xlValues命令上遇到运行时错误1004,但我无法解决原因。

如何实现将所有数据粘贴为值并另存为新工作簿的目标?

2 个答案:

答案 0 :(得分:2)

你很近,只需要在wSheet旁边移动UsedRange

Sub MakeAllVals()
Dim wSheet As Worksheet

For Each wSheet In ActiveWorkbook.Worksheets
    With wSheet.UsedRange
        .Copy
        .PasteSpecial xlValues
    End With
Next wSheet

Application.Dialogs(xlDialogSaveAs).Show
End Sub

答案 1 :(得分:2)

您只需要粘贴到新工作表中的范围即可。目前,您不会在新书中粘贴,也不会在一定范围内粘贴。

Sub MakeAllVals()
    Dim oldBook As Workbook, oldSheet As Worksheet
    Dim newBook As Workbook, newSheet As Worksheet

    Set oldBook = ThisWorkbook      ' Set to the formula workbook you want to copy from
    Set newBook = Workbooks.Add     ' Make the new workbook you want only values in

    For Each oldSheet In oldBook.Sheets   ' Loop through all of the sheets in the formula book
        Set newSheet = newBook.Sheets.Add ' Make a new sheet in the newbook to add the values to

        newSheet.Name = oldSheet.Name & " Values" 
        oldSheet.UsedRange.Copy                   
        newSheet.Range("A1").PasteSpecial xlValues ' Paste in a range on the new sheet as Values
    Next oldSheet

    Application.Dialogs(xlDialogSaveAs).Show ' Show Save As Dialog window
End Sub