2017-04-03 66 views
0
Sub MakeTables() 
    Dim wbTarget As Object 

    Set wb = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\GenerateTablesFormulas.xlsx") 
    Set wbTarget = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\USDReport.xlsx") 

    With wb.Sheets("Sheet1").UsedRange 
    .Copy 

    ' Create the new sheet and name it at the end 

     With wbTarget.Sheets("HK").Range("D82:X97") 
     .PasteSpecial xlValues 
     .PasteSpecial xlFormats 
     End With 
    End With 

End Sub 

有人可以告訴我我在這裏犯了什麼錯誤。它給了我範圍類失敗的錯誤。謝謝粘貼範圍班級特殊方法失敗vba

,如果你想保持 複製範圍大小,然後
+0

你不能有'隨着wbTarget.Sheets( 「HK」)'內'隨着wb.Sheets( 「工作表Sheet1」)'是'另一個在Worksheet'另一個'Workbook'對象。您應該關閉第一個'With wb.Sheets(「Sheet1」)。UsedRange' with'End With',然後才能啓動第二個'With wbTarget.Sheets(「HK」)。Range(「D82:X97」) ' –

+0

我不認爲這是問題所在。我已經把它分離出來了,但是仍然得到了同樣的錯誤 – Desmond

+0

你在哪一行得到你的錯誤? –

回答

0

With wb.Sheets("Sheet1").UsedRange 
    .Copy 

    ' Create the new sheet and name it at the end 

    With wbTarget.Sheets("HK").Range("D82") '.Resize(.Rows.Count, .Columns.Count) '<--| you can omit the 'Resize' part but it can be useful to make it clear (code can be read in years to come) you want to stick to copied range size 
     .PasteSpecial xlValues 
     .PasteSpecial xlFormats 
    End With 
End With 
Application.CutCopyMode = False '<--| empty clipboard 

否則,如果你想force複製的範圍大小與待粘貼一個,那麼:

' Create the new sheet and name it at the end 

With wbTarget.Sheets("HK").Range("D82:X97") '<--| reference range you want to paste values to and keep sizes of 
    wb.Sheets("Sheet1").UsedRange.Resize(.Rows.Count, .Columns.Count).Copy '<--| copy the source sheet range with same sizes as referenced range 

    .PasteSpecial xlValues 
    .PasteSpecial xlFormats 
End With 
Application.CutCopyMode = False '<--| empty clipboard 
+0

@Desmond;你有沒有嘗試過這個解決方案? – user3598756