简体   繁体   English

excel vba 向下复制空白单元格

[英]excel vba copy down over blank cells

column A has data like this (ie frequent blank cells): A列有这样的数据(即频繁的空白单元格):

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:我正在尝试将其复制到 D 列中的新范围,但使其看起来像这样:

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) .我肯定会建议不要使用字符串连接来构建单元格地址,就像你在这里做的那样: 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.请改用.Cells.Resize.Offset方法。

Also, I would avoid using .Copy since this will make your data transit via the system's clipboard.另外,我会避免使用.Copy ,因为这将使您的数据通过系统的剪贴板传输。 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.最后,不是循环遍历单元格,而是一次将整个范围加载到Variant数组中,在那里执行所有循环和操作,最后一次将整个内容写入工作表,效率更高。 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

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

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