2014-09-12 110 views
0

我想從另一個Excel工作表粘貼值,但我的代碼在下面一直返回一個錯誤。我究竟做錯了什麼 ?VBA-粘貼值錯誤

設置tempWB = Application.Workbooks.Open(vrtSelectedItem)「這將打開工作簿參考

Sheets("Portfolio Worksheet 8.8").Select 'SELECT A SHEET if you need to 
Range("B16:B30").Select 'select SOME RANGE 
Selection.Copy 'COPY SOME RANGE 

mainWB.Activate 'activate your main workbook 
Sheets("Sheet1").Select 'select target sheet 
Range("C20").Select 'select target cell 
ActiveSheet.PasteSpecial xlPasteValues 'paste the data from the reference worksheet 

tempWB.Save 'save and close the reference workbook 
tempWB.Close 
+0

有什麼錯誤? – 2014-09-12 15:44:14

回答

0

它看起來並不像你聲明瞭變量 'mainWB'?

+0

對不起,我沒有把整個代碼,因爲它只需要粘貼功能需要空間代碼工作,當我做粘貼值它給了我一個錯誤 – Ian 2014-09-12 15:38:49

+0

嘗試:表(「Sheet1」)。範圍(「C20」) .PasteSpecial xlPasteValues Application.CutCopyMode = False – Uberzen1 2014-09-12 15:42:06

1

無需任何選擇或複製粘貼

Set tempWB = Application.Workbooks.Open(vrtSelectedItem) 

With tempWB.Sheets("Portfolio Worksheet 8.8").Range("B16:B30") 

    mainWB.Sheets("Sheet1").Range("C20").Resize(.Rows.Count, _ 
               .Columns.Count).Value = .Value 
End With 

tempWB.Save 'save and close the reference workbook 
tempWB.Close 
+0

謝謝將Sheet1範圍更改爲範圍(「B16:B30」)後工作 – Ian 2014-09-12 16:01:45

0

下面這工作,感謝的建議,但是如果我要複製的同時粘貼多個範圍。所以下面的代碼返回「Next for for」錯誤。我認爲,在**是造成問題

設置tempWB = Application.Workbooks.Open(vrtSelectedItem)代碼的第二部分「這將打開工作簿參考

   ' Sheets("Portfolio Worksheet 8.8").Select 'SELECT A SHEET if you need to 


       With mainWB.Sheets("Sheet1").Range("B16:B30") 

       tempWB.Sheets("Sheet5").Range("B16:B30").Resize(.Rows.Count, _ 
              .Columns.Count).Value = .Value 
       **With mainWB.Sheets("Sheet1").Range("D16:D30") 
       tempWB.Sheets("Sheet5").Range("D16:D30").Resize(.Rows.Count, _ 
              .Columns.Count).Value = .Value** 

       End With 

       tempWB.Save 'save and close the reference workbook 
       tempWB.Close 

     Next vrtSelectedItem 

    Else 'The user pressed Cancel. 
    End If 
End With 

Set fd = Nothing 'Set the object variable to Nothing. 

末次