VBA Paste Value to Next Empty Cell in a Range

与世无争的帅哥 提交于 2021-01-29 08:11:10

问题


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). 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. 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?


回答1:


Need to start at B16 in Sheet2 and look upwards:

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)




回答2:


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



回答3:


This will copy the value and paste it to the column B in Sheet 2.

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


来源:https://stackoverflow.com/questions/52727084/vba-paste-value-to-next-empty-cell-in-a-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!