复制多个行选择时调整单元格列的大小

时间:2013-03-25 19:15:35

标签: excel-vba vba excel

我一直收到错误1004"复制区域大小/形状不同"在这段代码上:

我已尝试在各个地方插入各种.pastespecials,.selection.autofit ......但我有点在黑暗中刺伤。

帮助?

Sub SaveData()

Dim rr As Range
Set rr = Selection

For Each Row In rr

   'error occurs here'
    Range("a" & i & ":BN" & i).Copy Worksheets("ArchiveData").Cells(Worksheets("ArchiveData").Rows.Count, "b").End(xlUp).Offset(1, 0) 
    Sheets("ArchiveData").Cells(Worksheets("archivedata").Cells(Rows.Count, 2).End(xlUp).Row, 1).Value = Date



    Next Row

End Sub

2 个答案:

答案 0 :(得分:0)

首先使用OPTION EXPLICIT! (工具>选项>编辑器>需要变量声明)

现在针对这个特殊问题(在Option Explicit on上就可以了。

Row中的

For Each Row In rr被视为变量或对象,而不是范围rr的行。

您需要使用的是

Dim rr As Range
Dim rrrow as Range

Set rr = Selection

For Each rrrow In rr.Rows

现在接下来的问题是i也没有标注尺寸,甚至没有值,因此它很可能是零或空(0或“”或NULL)

我想你想要继续这样的事情:

rrrow.Copy
With Worksheets("ArchiveData")
    .Range(........).PasteSpecial 'HERE YOU ONLY NEED TO SPECIFY THE TOP LEFT MOST CELL
End With

答案 1 :(得分:0)

尝试以下代码:

Sub SaveData()

    Dim rr As Range
    Set rr = Selection


    Dim wsht As Worksheet
    On Error Resume Next
    Set wsht = Worksheets("ArchiveData")
    On Error GoTo 0

    If wsht Is Nothing Then Exit Sub

    For i = 1 To rr.Rows.Count

        Range("a" & i & ":BN" & i).Copy wsht.Cells(wsht.Range("B65000").End(xlUp).Row + 1, 2)
        wsht.Cells(wsht.Cells(Rows.Count, 2).End(xlUp).Row, 1).Value = Date

    Next
End Sub