I am trying to write an excel macro that copies specific cells from one worksheet and pastes them in another. Unfortunately the code is not working and I can't see where I went wrong. Here is what I have:
Sub sbCopyRangeToAnotherSheet()
Range("A1").Select
Selection.Copy
Sheets("Sheet1").Select
lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
Range("B" & lMaxRows + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End
It is attempting to follow this pseudocode:
If a row in worksheet one has a number its first cell and is blank for the rest, copy that number and paste it into cell A1 of sheet two.
else move down one cell and check again
I assigned it to a button and runs when I click it. I get a debugging error on the "Selection.PasteSpecial...." line.
I have no experience programming and this is my first attempt.Sorry for any mistakes. Google searches on this topic have led me to sites that my work computer has blocked for some reason.
Thank you!
You are getting that error because your clipboard is getting empty by the time you are pasting.
My suggestion. Avoid the use of .Select . Define your objects and work with them. You may want to see this link
How to avoid using Select in Excel VBA macros
Once you have declared your objects, move the copy line just before you are pasting.
Or write something like this
lMaxRows = Sheets("Sheet1").Range("B" & _
Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Sheets("Blah Blah").Range("A1").Copy
Sheets("Sheet1").Range("B" & lMaxRows).PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.