excel - How to loop to copy data following blank cells in a column and paste it to last empty column?
问题描述
I need to copy a block of data in column A (which are in between blank spaces) and paste it to last empty column. Example: I have data in range A1:A18 and a blank cell, and again data in A20:A37 and 2 blank cells & and again data in A40:A57 & so on. I need to copy those data and paste in Column B, C, D....
The pattern of blank spaces is not uniform.
I did some research on the internet and created a code to paste manually selected data in column A to the last empty column. But the list is too long and I want to automate the process.
I tried this code to find blank spaces and copy data. It finds the last blank row and copies all data, popping up an error.
Sub Pasting_Data_to_last_column()
Dim xWs As Worksheet
Dim rng As Range
Dim lastCol As Long
Sheets("Input").Activate
Application.ScreenUpdating = False
'finds the number of the last column
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Range("A1", Cells(Rows.Count, 1).End(xlUp)).Copy
'paste the copied value to last empty column
Cells(1, lastCol + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
I believe this problem can be solved with a loop but I don't have any idea about that as I am new to VBA.
解决方案
Try this, which uses SpecialCells to extract blocks of cells (or Areas). It assumes the cells do not contain formulae so if this is not the case, will need changing.
Sub x()
Dim r As Long
For r = 2 To Columns(1).SpecialCells(xlCellTypeConstants).Areas.Count
Columns(1).SpecialCells(xlCellTypeConstants).Areas(r).Copy
Cells(1, Columns.Count).End(xlToLeft).Offset(, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Next r
End Sub
推荐阅读
- javascript - settimeout() 间隔是通过单击开始按钮来改变速度
- ios - NSString.boundingRect 在指定字体时失败,并显示“[NSNull renderingMode]: unrecognized selector sent to instance”
- java - 我不明白 System.out.println((char)b) 和 System.out.write((char)b) 之间的输出差异
- ruby-on-rails - Rails 5/rspec/capybara:如何为 AJAX 表单编写功能请求?
- c - 在阿姆斯壮数中没有得到想要的输出
- .net-core - 如何在 .NET Core 或 .NET Standard 中正确设置 Fody.Costura
- bdd - 如何在 Behave BDD 中处理这种背景案例
- postgresql - 从 sql 格式转储恢复 pythonanywhere 上的 postgresql
- python - 是否可以更改 Spacy 分词器的分词规则?
- javascript - 如何将ASCII码字符串转换为字符串?