[英]Copy the cell value to another cell if
I'm writing VBA in Excel and I have a cell with some numbers in it and I have a "shopping cart" range and I when I click on the button I want to copy the cell value to the "cart" but if the first row in the cart is already full it should move on the next row and do this until it finds a row that it empty and paste it in there.我在 Excel 中编写 VBA,我有一个单元格,里面有一些数字,我有一个“购物车”范围,当我点击按钮时,我想将单元格值复制到“购物车”,但如果第一个购物车中的一行已经满了,它应该移动到下一行并执行此操作,直到找到一行空的并将其粘贴在那里。
I tried to do it but got a problem我尝试这样做但遇到了问题
Sub Gumb1_Klikni()
Range("B1").Select
Selection.Copy
Range("J2").Select
If IsEmpty(ActiveCell) Then
Selection.PasteSpecial xlPasteAll
Else
Set nextcell = ActiveCell.Offset(1, 0)
Range(nextcell).Select
ActiveSheet.Paste
End If
End Sub
It gives me Error 1004 "Method 'Range' of object '_Global' failed" at它给了我错误 1004“对象'_Global'的方法'范围'失败”在
Range(nextcell).Select
If you would define Dim nextcell as Range
at the beginning of your Sub
, all you need to do is:如果您在Sub
的开头将Dim nextcell as Range
定义Dim nextcell as Range
,您需要做的就是:
nextcell.Select
However, you could use the "Cleaner" version below, without the need to use Select
or Selection
:但是,您可以使用下面的“Cleaner”版本,而无需使用Select
或Selection
:
Option Explicit
Sub Gumb1_Klikni()
Dim nextCell As Range
Range("B1").Copy
If IsEmpty(Range("J2")) Then
Range("J2").PasteSpecial xlPasteAll
Else
Set nextCell = Range("J2").Offset(1, 0)
nextCell.PasteSpecial
End If
End Sub
Edit 1: after PO clarification:编辑 1:在 PO 澄清后:
Sub Gumb1_Klikni()
Dim LastRow As Long
' get last row with data in column "J"
LastRow = Cells(Rows.Count, "J").End(xlUp).Row
If LastRow < 1 Then LastRow = 1
Range("B1").Copy
Range("J" & LastRow + 1).PasteSpecial xlPasteAll
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.