要在循环中复制和粘贴的宏

时间:2018-02-24 05:49:36

标签: excel excel-vba vba

对于你们中的许多人来说,这可能很简单。我需要将来自2个特定列的数据复制并粘贴到新的电子表格中;但是当宏到达数据末尾或单元格为空时,宏需要停止。

到目前为止代码看起来像这样:

Workbooks.Add
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!R1C1"
Range("A1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!RC1"
Range("B1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!R1C3"
Range("B1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!RC3"
Range("A1:B1").Select
Selection.Copy
Range("A2:A101").Select
ActiveSheet.Paste
Range("A1").Select
Windows("Muhanad_Reset_import-TEMPLATE.xlsx").Activate

我知道复制和粘贴代码的代码不能用于获得良好的结果。

1 个答案:

答案 0 :(得分:0)

你的意思是这样的代码:

Sub Test()
    Dim lr      As Long
    Dim i       As Long

    lr = ThisWorkbook.Worksheets("Reset_import-Raw Data").Cells(Rows.Count, 1).End(xlUp).Row
    Workbooks.Add

    With ActiveSheet.Range("A1:A" & lr)
        .Formula = "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!$A1"
        .Offset(, 1).Formula = "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!$C1"
    End With

    Windows("Muhanad_Reset_import-TEMPLATE.xlsm").Activate
End Sub