复制并粘贴在VBA使用相对引用? (错误代码1004)

新的这个论坛,所以很抱歉,如果这是closures。 我试图做一个简单的单元格值从一本书的工作表复制到另一个工作表,但需要使用相对单元格引用作为将根据input的数据复制/粘贴的行数变化。

(非常简单)代码到目前为止是:

Sub SuitorList() 'Defining Variables Dim Row As Integer Row = Sheets("References").Cells(6, 2).Value 'Copying Statistics Sheets("Charts").Range(Cells(1, 1), Cells(Row, 1)).Value = _ Sheets("Data").Range(Cells(1, 1), Cells(Row, 1)).Value End Sub 

当我使用绝对单元格引用(即“B1:B7”)时,此代码工作正常,但是当我使用相对引用时,我收到错误代码1004:应用程序定义或对象定义的错误。

有什么想法吗?

如果你要将数据从一张纸复制到另一张纸上,并且复制/粘贴的数据量总是在变化,那么我会这样做。 过滤您的select表单中的数据,然后通过查找第一个空白单元格将其复制并粘贴到目标表单。 你可能不得不惹恼这一点,但这是一个好的开始。

 'Defining Variables Dim Row As Integer Row = Sheets("References").Cells(6, 2).Value 'switches the sheet Sheets("Charts").Select 'filters a table based on the value of the Row variable ActiveSheet.ListObjects("Table1").range.AutoFilter Field:=1, Criteria1:= _ range("Row"), Operator:=xlAnd 'moves to the first cell in the filtered range range("A1").Select 'selects all values in the range and copies to clipboard range(Selection, Selection.End(xlDown)).Select Application.CutCopyMode = False Selection.Copy 'switches the sheet back to data sheet Sheets("Data").Select 'finds the first blank cell in the declared range you want to paste into ActiveSheet.range("A:A").Find("").Select 'pastes the selection ActiveSheet.Paste 

谢谢您的帮助。 我能够find一个解决使用下面的代码:

 Sub SuitorList() 'Defining Variables Dim Row As Integer Row = Sheets("References").Cells(6, 2).Value 'Copying Statistics For i = 1 To Row Sheets("Charts").Range("A" & i).Value = Sheets("Data").Range("A" & i).Value Next End Sub 

替代scheme:

如果您不是Loops的粉丝,请使用Worksheet.Cells属性

 Sub SuitorList() 'Defining Variables Dim Row As Integer Set wd = ThisWorkbook.Worksheets("Data") Set wc = ThisWorkbook.Worksheets("Charts") Row = Sheets("References").Cells(6, 2).Value 'Copying Statistics Range(wd.Cells(1, 1), wd.Cells(Row, 1)).Copy Destination:=Range(wc.Cells(1, 1), wc.Cells(Row, 1)) End Sub