I know that I can accomplish this via iterating over the first range, but I’m curious to see if I can accomplish it using the SpecialCells property.
Say I have a column of names with empty cells in between:
A B C
Jon
Jim
Sally
Jane
Mary
If I want to use VBA to copy over just the used cells, I can say
Range("A1:A8").SpecialCells(xlCellTypeConstants, xlTextValues).Copy
Range("C1:C"&Range("A1:A8").SpecialCells(xlCellTypeConstants, xlTextValues).Count).PasteSpecial
and end up with
A B C
Jon Jon
Jim Jim
Sally Sally
Jane
Jane Mary
Mary
Instead, I’d like to be able to do this without having to paste a range anywhere.
What I want to be able to do is have a range containing [Jon,Jim,Sally,Jane,Mary], but if I try Set rng = Range("A:A").SpecialCells(xlCellTypeConstants,xlTextValues), I either end up with the spaces as elements of the range, or using a hard-coded range of cells, with one that counts only [Jon, Jim, Sally] before it hits the space.
I’d like to be able to use the range elsewhere in the code, and I think the SpecialCells is a nice compact way of doing it, but is my only alternative to do it in a loop and compare cells as <> ""?
Consider the following code:
The only reliable piece of information in the above is
r.Cells.Count. TheRowsget cut at the first blank. I imagine this confuses the whole pasting process. So, you can’t pasterdirectly to the worksheet.You could transfer it to a Variant array, and then slap* that onto the sheet. But how to do this? Well,
r.Cellsis akin to a collection. Perhaps convert it to an array like this:No need to check for empty cells.
You could also use Chip Pearson’s
CollectionToArrayprocedure, which is basically a fancier implementation of the above code, maybe with a bit of modification.By the way, checking for
<> ""will not reject cells whose value is an empty string"". If you must check for truly empty/"blank" cells, thenIsEmptyis safer.*Credits to @Issun for coining "slap" in this context.