2017-09-29 101 views
1

我無法在工作簿中複製範圍。有類似的帖子(VBA copy-paste offset to another workbook)與此相關,但似乎沒有幫助與應用程序定義或對象定義的錯誤。VBA:跨工作簿複製粘貼範圍對象定義的錯誤

我已經試過這

 Set wbSource = Workbooks("Source.xlsx") 
     Set wbTarget = Workbooks("Target.xlsx") 
     Set wbSource_WS = wbSource.Worksheets("Source") 
     Set wbSTarget_WS = wbTarget.Worksheets("Target") 

     wbSource_WS.Activate 
     wbSource_WS.Range(Cells(Row_SourceStart, Col_Source), Cells(Row_SourceEnd, Col_Source)).Copy 
     wbTarget_WS.Activate 
     wbSTarget_WS.Range(Cells(Row_TargetStart, Col_TargetStart), Cells(Row_TargetStart, Col_TargetEnd)).PasteSpecial Paste:=xlPasteValues 

這也太:

 wbSource_WS.Range(Cells(Row_SourceStart, Col_Source), Cells(Row_SourceEnd, Col_Source)).Copy Destination:= _ 
     wbSTarget_WS.Range(Cells(Row_TargetStart, Col_TargetStart), Cells(Row_TargetStart, Col_TargetEnd)).PasteSpecial(Paste:=xlPasteValues, Transpose:=True) 
+0

嘗試使用此... 'wbSTarget_WS.Range(細胞(Row_TargetStart,Col_TargetStart))PasteSpecial的(糊劑:= xlPasteValues,移調:= TRUE)。' –

+0

可以有源和目標範圍的大小不匹配的誤差... –

+0

我調試了我的代碼。源和目標範圍是相同的。 – doyz

回答

1

您需要在範圍完全申報對象:

wbSource_WS.Activate 
wbSource_WS.Range(Cells(Row_SourceStart, Col_Source), Cells(Row_SourceEnd, Col_Source)).Copy 

應該像這樣:

wbSource_WS.Activate 
wbSource_WS.Range(wbSource_WS.Cells(Row_SourceStart, Col_Source), wbSource_WS.Cells(Row_SourceEnd, Col_Source)).Copy 
012需要個

在.range每個.cells被束縛:wbSource_WS

會稍微簡單/清潔劑只使用with語句:

With wbSource_WS 
    .Range(.Cells(Row_SourceStart, Col_Source), .Cells(Row_SourceEnd, Col_Source)).Copy 
End With 
+0

您會爲所有實例執行此操作;只是以第一例爲例。 – Cyril

+0

這工作在清除「對象定義的錯誤」,但現在出現一個新的錯誤「無法獲得範圍類的pastespecial屬性」,我現在正在嘗試修復 – doyz

+0

@diana你是否嘗試粘貼範圍沒有.pastespecial看看它是否有效?對於完全定義的範圍,您可能需要選擇所需範圍的左上角單元格進行粘貼。 – Cyril

0

有一個在你的代碼一個錯字。

Set wbSource = Workbooks("Source.xlsx") 
    Set wbTarget = Workbooks("Target.xlsx") 
    Set wbSource_WS = wbSource.Worksheets("Source") 
    Set wbSTarget_WS = wbTarget.Worksheets("Target") 

    wbSource_WS.Activate 
    wbSource_WS.Range(Cells(Row_SourceStart, Col_Source), Cells(Row_SourceEnd, Col_Source)).Copy 
    **wbSTarget_WS.Activate** 
    wbSTarget_WS.Range(Cells(Row_TargetStart, Col_TargetStart), Cells(Row_TargetStart, Col_TargetEnd)).PasteSpecial Paste:=xlPasteValues 

我跑這個小小的變化,它沒有產生任何錯誤。

我會建議你使用Option Explicit。這將防止再次發生此錯誤。 Excel會指出在運行VBA程序之前還有一個未聲明的變量。

相關問題