Excel在使用vba刷新工作表时将数据从一个工作表复制到另一个工作表

时间:2016-11-19 16:56:13

标签: excel vba excel-vba

我想将特定单元格中“Sheet1”的数据复制到“Sheet2”中的下一个可用空单元格,以便更改(F9)导致从Sheet1复制数据并在Sheet2中填充数据列

到目前为止,我有以下内容,它会引发错误:(.Rows.Count

每次在'F9'上刷新工作簿时,是否可以弹出Sheet2中的列?

'In this example I am Copying the Data from Sheet1 (Source) to Sheet2              (Destination)
Private Sub worksheet_calculate()
'Method 2
'Copy the data
Sheets("Sheet1").Range("I1").Copy
'Activate the destination worksheet
Sheets("Sheet2").Activate
'Select the target range
Sheet2.Cells(.Rows.Count, "A").End(xlUp).Row
'Paste in the target destination
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

3 个答案:

答案 0 :(得分:0)

您错误地选择了上次使用的行。试试这个:

Private Sub worksheet_calculate()
Dim lstrow As Integer
'Method 2
'Copy the data
Sheets(1).Range("I1").Copy
'Activate the destination worksheet
Sheets(2).Activate
'Select the target range
lstrow = Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
'Paste in the target destination
ActiveSheet.Cells(lstrow + 1, 1).Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

答案 1 :(得分:0)

尝试下面的代码,它会将Cell I1从“Sheet1”复制到“Sheet 2”中A列的下一个可用行。

最好避免使用ActivateActiveSheet,而只需复制>粘贴在一行中(如下面的代码所示)

不确定为什么要在worksheet_calculate事件中使用此代码。

'In this example I am Copying the Data from Sheet1 (Source) to Sheet2 (Destination)

Private Sub worksheet_calculate()

Dim LastRow As Long

With Sheets("Sheet2")
    ' find last row in Sheet 2
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

'Copy the data and Paste in Sheet 2 (+1 for next avaialble row)
Sheets("Sheet1").Range("I1").Copy Sheets("Sheet2").Range("A" & LastRow + 1)

Application.CutCopyMode = False

End Sub

编辑1:

根据PO更新信息修改代码:

为了避免F9无限循环,请使用Application.EnableEvents = False内的Sub

Private Sub worksheet_calculate()

'In this example I am Copying the Data from Sheet1 (Source) to Sheet2 (Destination)
Dim LastRow As Long

Application.EnableEvents = False

With Sheets("Sheet2")
    ' find last row in Sheet 2
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row              
    ' copy the values only from "Sheet1" to "Sheet2"
    .Range("A" & LastRow + 1).Value = Sheets("Sheet1").Range("I1").Value
End With

Application.CutCopyMode = False    
Application.EnableEvents = True

End Sub

您可以在@ user3598756写道:

的一行中执行Copy>Paste
With Worksheets("Sheet2")
   .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Value = Worksheets("Sheet1").Range("I1").Value
End With

答案 2 :(得分:0)

您是否有兴趣仅粘贴值

Private Sub worksheet_calculate()
   With Worksheets("Sheet2")
       .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Value = Worksheets("Sheet1").Range("I1").Value
    End With
End Sub