2015-10-28 112 views
0

我試圖自動化一個過程,該過程涉及將粘貼數據從一個工作簿粘貼到新工作簿。我已經能夠在這裏和其他地方的論壇中找到的代碼片段放在一起。但是,嘗試運行該過程時,我收到「運行時錯誤1004」。有什麼建議麼?將選擇從一個工作簿複製粘貼到另一個

Option Explicit 
Dim wbI As Workbook, wbO As Workbook, wsI As Worksheet, wsO As Worksheet 
Dim wbName As String 
Sub transferit() 

wbName = InputBox("Enter name", "name") 

'~~> 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 
'~~> Set the relevant sheet to where you want to paste 
Set wsO = wbO.Sheets("Sheet1") 

With wbO 
    '~~>. Save the file 
    .SaveAs Filename:="D:\Documents\Output\wbName 
End With 

With wsI 
    Call RangeSelectionPrompt 
    Selection.Copy 
End With 

With wsO 
    '~~> Paste it in say Cell A1. Change as applicable 
    .Range("A1").PasteSpecial xlPasteValues 
End With 
End Sub 

Sub RangeSelectionPrompt() 
    Dim rng As Range 
    Set rng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8) 
End Sub 
+0

必須是一個錯字,但有一個「丟失在'.SaveAs ...'行。 –

+0

結束,你不'rng.Select'的RangeSelectionPrompt內,因此呼叫不沒有用處。 –

回答

0

你需要的全局變量?這是不可能的,把它們移到Sub中。你沒有爲.SaveAs正確拼接文件名,並且你沒有複製你期望的文件... 這裏是我的代碼,它仍然缺少對錯誤的一些控制。

Sub transferit() 

     Dim wbI As Workbook, wbO As Workbook, wsI As Worksheet, wsO As Worksheet 
     Dim wbName As String 
     wbName = InputBox("Enter name", "name") 

     '~~> 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 
     '~~> Set the relevant sheet to where you want to paste 
     Set wsO = wbO.Sheets("Sheet1") 

     With wbO 
      '~~>. Save the file 
      .SaveAs Filename:="D:\Documents\Output\" & wbName 
     End With 

     RangeSelectionPrompt.Copy 

     With wsO 
      '~~> Paste it in say Cell A1. Change as applicable 
      .Range("A1").PasteSpecial xlPasteValues 
     End With 
    End Sub 

    Function RangeSelectionPrompt() As Range 
     Set RangeSelectionPrompt = Application.InputBox("Select a range", "Obtain Range Object", Type:=8) 
    End Function 


    RangeSelectionPrompt.Copy 

    With wsO 
     '~~> Paste it in say Cell A1. Change as applicable 
     .Range("A1").PasteSpecial xlPasteValues 
    End With 
End Sub 

Function RangeSelectionPrompt() As Range 
    Set RangeSelectionPrompt = Application.InputBox("Select a range", "Obtain Range Object", Type:=8) 
End Function 
相關問題