2012-09-09 142 views
6

這應該是非常簡單的,但我一直在拖網論壇和SO幾個小時的答案找到沒有運氣的答案,所以我(勉強)創建一個我自己的問題。複製範圍和粘貼到新的工作簿

我想要做的只是創建一個新的工作簿,並將另一個工作簿的範圍粘貼到該工作簿中。聽起來很簡單..?

我原來的工作簿,讓我們打電話給Book1。我正在嘗試創建一個新的工作簿Book2,該工作簿將複製單元格A1:B10的

這裏是我的代碼一個版本(從第一冊開放):

Range("A1:B10").Copy 
Set NewBook = Workbooks.Add 
    With NewBook 
     .SaveAs Filename:="Book2.xls" 
    End With 
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
    :=False, Transpose:=False 

這給出了一個「Range類的PasteSpecial的失敗」錯誤。我曾嘗試以下修正,沒有運氣:

  • 增加了「工作簿(‘Book2.xls中’)啓動。」在PasteSpecial的線
  • 試圖」去除多餘的參數的代碼
  • .Paste 「而不是」 .PasteSpecial」
  • 改變‘Selection.PasteSpecial’到‘ActiveSheet.PasteSpecial’
  • 顯式引用複製範圍,包括工作簿和紙基準
  • 首先創建新的工作簿,則執行與c opy,然後重新激活新的工作簿並粘貼

上述解決方案都無效......在此階段的任何智慧都會被感激地接收!

回答

16

這是你正在嘗試?我已經評論了代碼,以便在理解代碼的功能時不會有任何問題。

Option Explicit 

Sub Sample() 
    Dim wbI As Workbook, wbO As Workbook 
    Dim wsI As Worksheet, wsO As Worksheet 

    '~~> Source/Input Workbook 
    Set wbI = ThisWorkbook 
    '~~> Set the relevant sheet from where you want to copy 
    Set wsI = wbI.Sheets("Sheet1") 

    '~~> Destination/Output Workbook 
    Set wbO = Workbooks.Add 

    With wbO 
     '~~> Set the relevant sheet to where you want to paste 
     Set wsO = wbO.Sheets("Sheet1") 

     '~~>. Save the file 
     .SaveAs Filename:="C:\Book2.xls", FileFormat:=56 

     '~~> Copy the range 
     wsI.Range("A1:B10").Copy 

     '~~> Paste it in say Cell A1. Change as applicable 
     wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _ 
     SkipBlanks:=False, Transpose:=False 
    End With 
End Sub 
3

這適用於我。

Private Sub CommandButton1_Click() 
Dim newWB As Workbook, currentWB As Workbook 
Dim newS As Worksheet, currentS As Worksheet 

'Copy the data you need 
Set currentWB = ThisWorkbook 
Set currentS = currentWB .Sheets("Sheet1") 
currentS .Range("A:M").Select 
Selection.Copy 

'Create a new file that will receive the data 
Set newWB = Workbooks.Add 
    With newWB 
     Set newS = newWB.Sheets("Sheet1") 
     newS.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _ 
     SkipBlanks:=False, Transpose:=False 
     'Save in CSV 
     Application.DisplayAlerts = False 
     .SaveAs Filename:="C:\Temporary.csv", FileFormat:=xlCSV 
     Application.DisplayAlerts = True 
    End With 
End Sub 
相關問題