简体   繁体   English

VBA值粘贴到范围中的下一个空单元格

[英]VBA Paste Value to Next Empty Cell in a Range

I'm trying to copy and paste a value from one sheet (C39 on Sheet1) to the next empty cell within a range on another sheet (B6 through B18 on Sheet2). 我正在尝试将值从一张纸(Sheet1上的C39)复制并粘贴到另一张纸(Sheet2上的B6至B18)范围内的下一个空单元格。 Here's the code I'm using. 这是我正在使用的代码。

Sheets("Sheet1").Range("C39").Copy
With Sheets("Sheet2").Range("B6:B18").End(xlUp).Offset(1)
.PasteSpecial Paste:=xlPasteValues
End With
End Sub

When I run this macro, it continues to overwrite B6 on Sheet2. 当我运行此宏时,它将继续覆盖Sheet2上的B6。 Ideally, it'd see there's a value in B6 and paste into B7, and then B8, etc. What can I do to correct this? 理想情况下,它会看到B6中有一个值并将其粘贴到B7中,然后粘贴到B8中,等等。我该怎么做才能更正此错误?

You can set values equal to each other and not copy/paste. 您可以将值设置为彼此相等,但不能复制/粘贴。 Although on a cell by cell basis, the efficiency gain is essentially non existent. 尽管在逐个单元的基础上,效率增益基本上不存在。 On larger scales, this will save memory 在更大范围内,这将节省内存

Sub dural()

Sheets("Sheet2").Range("B16").End(xlUp).Offset(1, 0).Value = Sheets(“Sheet1”).Range(“C39”).Value

End Sub

Need to start at B16 in Sheet2 and look upwards: 需要从Sheet2的 B16开始并向上看:

Sub dural()
    Dim r1 As Range, r2 As Range
    Set r1 = Sheets("Sheet1").Range("C39")
    Set r2 = Sheets("Sheet2").Range("B16").End(xlUp).Offset(1, 0)
    r1.Copy r2
End Sub

(similar for PasteSpecial) (与PasteSpecial类似)

This will copy the value and paste it to the column B in Sheet 2. 这将复制该值并将其粘贴到工作表2中的B列中。

Sub CopyPaste()

Dim lrow As Integer
Sheets("Sheet1").Range("C39").Copy - What cell value to copy
lrow = 18 'End row on Sheet2
For i = 6 To 18 'Loop from row 6 to 18
    If Cells(i, 2) = "" Then 'If cell is empty then paste new value
    Sheets("Sheet2").Range(Cells(i, 2), Cells(i, 2)).PasteSpecial xlPasteValues
    End If
Next i
End Sub

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

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