VBA:跨工作簿对象定义的错误复制粘贴范围

我无法在工作簿中复制范围。 有类似的post( 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) 

您需要完全声明范围内的对象:

  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 

.range中的每个.cell都需要绑定到:wbSource_WS

只要使用With语句会更简单一些:

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

你的代码中有一个错字。

 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 

我用这个小小的变化来运行它,并没有产生任何错误。

我会build议你使用Option Explicit。 这将防止这个错误再次发生。 Excel会指出在运行VBA程序之前还有一个未声明的variables。