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开发者_JAVA技巧").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 e.g. 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
精彩评论