2014-10-27 81 views
0

我試圖創建一個VBA腳本,將整個工作簿中的所有數據複製爲值粘貼,然後另存爲新工作簿,從而刪除所有公式。複製所有值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,但我不明白爲什麼。

我該如何實現將所有數據粘貼爲值並保存爲新工作簿的目標?

+0

可能重複的:http://stackoverflow.com/questions/20671795/how-to-remove-formulas-from-sheet-but-keep-their-calculated-values – 2014-10-27 12:20:18

回答

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 
2

你接近只需要UsedRange未來拉昇至wSheet

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