Excel VBA复制数据报错:对象不支持该属性或方法
问题解决:VBA复制行报错“对象不支持该属性或方法”
错误原因
报错行的CopyAfter并非VBA中Range或Row对象的合法方法,这是触发报错的直接原因。VBA里复制单元格/行到目标位置,正确方式是使用Copy方法并指定Destination参数,或结合Insert实现插入操作。
代码修正方案
核心错误修正
将报错代码行替换为:
sourceRange.Rows(currentRow).EntireRow.Copy Destination:=destinationRange
额外优化与修正
原代码存在两处可优化/修正的细节:
- 原
sourceRange定义为A106:A110,后续还要调用EntireRow,可直接将sourceRange定义为目标行范围,简化代码:Set sourceRange = Worksheets("Sheet1").Rows("106:110") - MsgBox提示文本为“Sheet DCF_Consolidated not found”,但代码实际查找的是Sheet2,属于提示文本错误,需统一名称。
完整修正代码
Sub CopyData() Dim sourceRange As Range ' 直接定义为目标行范围,无需后续调用EntireRow Set sourceRange = Worksheets("Sheet1").Rows("106:110") ' 获取目标工作表 Dim destinationSheet As Worksheet On Error Resume Next Set destinationSheet = Worksheets("Sheet2") On Error GoTo 0 If destinationSheet Is Nothing Then ' 修正提示文本,与查找的工作表名称一致 MsgBox "Sheet2 not found. Skipping data copying." Exit Sub End If ' 复制数据到目标工作表的起始行 Dim startingRow As Long startingRow = 5 ' 遍历源数据行 Dim currentRow As Integer For currentRow = 1 To sourceRange.Rows.Count Dim destinationRow As Long destinationRow = startingRow + currentRow - 1 Dim destinationRange As Range Set destinationRange = destinationSheet.Rows(destinationRow) ' 使用正确的Copy方法指定目标位置 sourceRange.Rows(currentRow).Copy Destination:=destinationRange Next currentRow End Sub
高效简化写法(无需循环)
若仅需将106-110行一次性复制到Sheet2第5行开始的位置,无需循环,一行代码即可完成,效率更高:
Sub CopyDataFast() Dim sourceSheet As Worksheet Dim destinationSheet As Worksheet Set sourceSheet = Worksheets("Sheet1") On Error Resume Next Set destinationSheet = Worksheets("Sheet2") On Error GoTo 0 If destinationSheet Is Nothing Then MsgBox "Sheet2 not found. Skipping data copying." Exit Sub End If ' 一次性复制整行到目标位置 sourceSheet.Rows("106:110").Copy Destination:=destinationSheet.Rows(5) End Sub
内容的提问来源于stack exchange,提问作者Maverick
相关产品推荐
相关产品推荐

