Below is the code which I am using to copy cells from one sheet and paste in to another.
Sheets("codes").Select
Range("A5:A100").Select
Selection.Copy
Sheets("Sheet2").Select
Range("B28").Select
ActiveSheet.Paste
The problem with this is some cells in this range are blank but I do not want them to be copied to Sheet2. I have got some idea from here but this method is too long. Is there a way I can iterate on the selection and check if the value is non-empty and paste. This way I can also paste some other text (eg #NA) in the blank cells.
Easy:
I used
xlCellTypeConstants
but there are many other possibilities.Sheet1
is generally equivalent toSheets("Sheet1")
. The first one is the name in the VBE (programmer view), the second is the name in the user interface (user view). I generally prefer the fiirst syntax because it is shorter and allows renaming the sheets (for the user) without impacting the code.If you don't need formatting I'd use the following. All it does is copy the range you specify on the worksheet to a variable, loop through that variable, check for cells that are empty and put in whatever string you like. It's nice and quick. If you want to preserve the formatting, you can paste special just the formats to the output range.
And call it with:
Looks like you may be making some common rookie mistakes here (it's okay we all did it).
VBA example with line-by-line explanations
TIP: Try not to use "Select" or "Copy". Why use select when all you have to do is reference the cells themselves? For example, instead of using
Just use
I did the same thing all the time when I first started, and it never works out right. "Select" causes errors left and right. Use my code, read the comments, and you'll be fine. A quick WARNING: I don't have Excel on this computer so I couldn't test the code. If it doesn't work for some reason, leave me a comment and tomorrow I'll fix it at work.
The above code will omit blank cells completely when copying the data over to your second sheet. If you want to input a certain text for blank cells instead (like "N/A"), then you can use the following: