Looping Excel Macro to move contents of one cell to another
I had to send some data to a vendor for my job in an Excel spreadsheet. When I created the spreadsheet from the data some of the columns were shifted and things didn’t line up nicely. The data was small enough, but I didn’t want to spend all day shifting the columns Plus I am a programmer and it is always more fun to see if I can automate the process! This was more of a test to see if it could be done this way. I am sure there are easier ways to accomplish this directly from SQL. I have written stuff as Excel Macros before, but once again and the reason I started this blog was because I don’t want to forget how I figured out some of this stuff and if anyone else can benefit from these little examples So here is a simple looping Excel macro to move contents of one cell to another. I am restricting it to anything over 3 characters and should move it from column “A” to column “C”
So I know I did this a different way once before, but again my memory is short. This one way to get it accomplished:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Sub Macro2() Do If (Len(ActiveCell.Value) > 3) Then Selection.Cut Range(ActiveCell.Offset(0, 3).Address).Select ActiveSheet.Paste ActiveCell.Offset(0, -3).Select</code> <code>End If </code><code> ActiveCell.Offset(1, 0).Select Loop Until IsEmpty(ActiveCell) End Sub |
Looping over each row is not the fastest way to move things over, but if you need to check each cell in a column for a value it is still the only way that I can think of to get the job done. Looping is one of the slowest operations you can do in programming, but sometimes it is just necessary to get the job done. Hopefully this will help you move content around in your macro. Please add a comment if you know of another way to accomplish this and I will gladly update the post