简体   繁体   中英

excel vba copy down over blank cells

column A has data like this (ie frequent blank cells):

HEADING  <-- this is A1
kfdsl
fdjgnm
fdkj


gdfkj
4353

fdjk  



blah     <-- this is A14 

I'm trying to copy it to a new range in the D column but make it appears like this:

HEADING  <-- this is D1
kfdsl
fdjgnm
fdkj
fdkj
fdkj
gdfkj
4353
4353
fdjk  
fdjk
fdjk
fdjk
blah     <-- this is D14 

here is my code so far:

For i = 0 To UBound(origincells) 
 numrows = originsheet.Range(Left(origincells(i), 1) & "65536").End(xlUp).Row - 1
 originsheet.Range(origincells(i) & ":" & Left(origincells(i), 1) & numrows).Copy
 destsheet.Range(destcells(i) & ":" & Left(destcells(i), 1) & (Val(Right(origincells(i), 1)) + numrows)).PasteSpecial
Next

I would definitely advise against using string concatenation to build cell addresses, like you do here: Range(origincells(i) & ":" & Left(origincells(i), 1) & numrows) . This is unnecessarily messy, hard to write, and hard to read. Use eg the .Cells , .Resize , and .Offset methods instead.

Also, I would avoid using .Copy since this will make your data transit via the system's clipboard. Other applications may read from and write to the clipboard at the same time, and this will result in wild and unpredictable behaviour.

Finally, instead of looping through cells, it is more efficient to load the entire range at once into a Variant array, do all your looping and manipulations there, and finally write the whole thing to your sheet at once. This is the approach I use below.

This will do the trick:

Dim varData As Variant
Dim i As Long

varData = Sheet1.Range("A1:A14") '// Read in the data.

For i = LBound(varData, 1) + 2 To UBound(varData, 1)
    If IsEmpty(varData(i, 1)) Then
        '// Cell is empty. Copy value from above.
        varData(i, 1) = varData(i - 1, 1)
    End If
Next i

'// Write result to sheet.
Sheet1.Range("D1").Resize(UBound(varData, 1) - LBound(varData, 1) + 1, 1) _
    = varData

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