我们的办公室最近更新为Excel 2013,而在2010版中运行的代码无法正常工作。我在这里搜索了几个线程,但还没有找到适用于这种特殊情况的解决方案。VBA - 将可变行数从工作簿复制到另一个
代码从打开的工作簿中识别并复制一系列单元格,并将它们记录到第二个工作簿中,一次一个单元格区域。它被设置为一次只复制一行的原因是因为要复制的行数随时间而变化。自2013年更改以来,Selection.PasteSpecial函数一直在触发调试提示。
实际上,工作表被用作路由表单。填好后,我们运行代码并将所有相关信息保存在单独的工作簿中。由于它是一个路由表单,其上的人数会有所不同,我们需要为每个人排一行,以便跟踪他们的“状态”。
代码:
Sub Submit()
'Transfer code
Dim i As Long, r As Range, coltoSearch As String
coltoSearch = "I"
'Change i = # to transfer rows of data. Needs to be the first row which copies over.
'This is to identify how many rows are to be copied over. If statement ends the for loop once an "empty" cell is reached
For i = 50 To Range(coltoSearch & Rows.Count).End(xlUp).Row
Set r = Range(coltoSearch & i)
If Len(r.Value) = 0 Then
Exit For
End If
'Copies the next row on the loop
Range(Cells(i, 1), Cells(i, 18)).Copy
'open the workbook where row will be copied to
Workbooks.Open FileName:= _
"Workbook2"
'definition for the first empty row in Workbook 2, or the row under the last occupied cell in the Log
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'selects the first cell in the empty row
ActiveSheet.Cells(erow, 1).Select
' Pastes the copied row from Workbook 1 into Workbook 2. First line is highlighted when debugging
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False
'moves to the next row
Next i
有什么想法?我接受所有选择。谢谢你的时间。
您收到了什么错误? – asp8811
错误信息如下:“运行时错误”1004“范围类的PasteSpecial方法失败” –
“ActiveSheet.Cells(erow,1).Select”只选择一个单元格,但您的注释读取''粘贴复制的行.. .'。无论如何,避免使用'select'并创建变量来保存你的范围。 – findwindow