繁体   English   中英

Excel使用VBA将数据从一张纸复制到工作表上的另一张

[英]Excel copy data from one sheet to another on worksheet refresh with 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

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

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

试试下面的代码,它将单元格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:

根据采购订单更新信息修改代码:

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

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

您可以在一行中执行“ Copy>Paste ,就像@ user3598756写道:

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

您应该只对粘贴值感兴趣吗

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM