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

Blu*_*3k1 12 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
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能粘贴这些值?

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

Dmi*_*liv 22

你可以改变

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
Run Code Online (Sandbox Code Playgroud)

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
Run Code Online (Sandbox Code Playgroud)

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

请尝试使用此代码:

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
Run Code Online (Sandbox Code Playgroud)

注意,上面的代码确定DB了列A(变量lastrowDB)中工作表上的最后一个非空行.如果您需要在工作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
Run Code Online (Sandbox Code Playgroud)

您也可以使用下一种方法Copy/PasteSpecial.更换

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
Run Code Online (Sandbox Code Playgroud)

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