将范围和粘贴值复制到另一个工作表的特定范围中

时间:2014-02-08 15:52:28

标签: excel vba excel-vba

我正在尝试使用excel宏工作,但是我遇到了从包含公式的单元格中复制值的问题。

到目前为止,这就是我所拥有的,并且它与非公式细胞一起工作正常。

Sub Get_Data()
Dim lastrow As Long

lastrow = Sheets("DB").Range("A65536").End(xlUp).Row + 1

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
Range("C3:C65536").Copy Destination:=Sheets("DB").Range("A" & lastrow)
Range("D3:D65536").Copy Destination:=Sheets("DB").Range("C" & lastrow)
Range("E3:E65536").Copy Destination:=Sheets("DB").Range("P" & lastrow)
Range("F3:F65536").Copy Destination:=Sheets("DB").Range("D" & lastrow)
Range("AH3:AH65536").Copy Destination:=Sheets("DB").Range("E" & lastrow)
Range("AIH3:AI65536").Copy Destination:=Sheets("DB").Range("G" & lastrow)
Range("AJ3:AJ65536").Copy Destination:=Sheets("DB").Range("F" & lastrow)
Range("J3:J65536").Copy Destination:=Sheets("DB").Range("H" & lastrow)
Range("P3:P65550").Copy Destination:=Sheets("DB").Range("I" & lastrow)
Range("AF3:AF65536").Copy Destination:=Sheets("DB").Range("J" & lastrow).

End Sub

如何制作它以粘贴值?

如果可以更改/优化,我也会感激。

2 个答案:

答案 0 :(得分:21)

您可以更改

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

顺便说一句,如果你有xls文件(excel 2003),如果你的lastrow会更大,你就会收到错误。

尝试使用此代码:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

注意,上面的代码确定了DB列{变量AlastrowDB表上的最后一个非空行。如果您需要在DB表中找到每个目标列的lastrow,请使用下一个修改:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

您也可以使用下一种方法Copy/PasteSpecial。取代

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

答案 1 :(得分:0)

如果您将工作表中的每列复制到不同的工作表怎么样? 示例:mysheet的行B到sheet1的行B,mysheet的行C到表2的行B ......

相关问题