简体   繁体   中英

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

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:

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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