Excel - Macro to rearrange/add columns in all the sheets based on column header

Hi,

I need to rearrange columns on many sheets in a certain order based on
on column header.
For example, my columns might come into my spreadsheet as
C,B,D,G,A,H,I,F , or as F,B,C,A,D  etc.
I want them all sorted say A,B,C,D - the rest of the columns is
irrelevant.

How do I accomplish this ?
TIA
0
avi
2/17/2010 1:34:42 PM
excel.programming 6508 articles. 2 followers. Follow

9 Replies
1645 Views

Similar Articles

[PageSpeed] 51

What about the sort function Data/Sort prior to xl2007.  I recorded a
macro while doing this:

Selection.Sort Key1:=3DRange("B4"), Order1:=3DxlAscending,
Header:=3DxlGuess, _
        OrderCustom:=3D1, MatchCase:=3DFalse, Orientation:=3DxlLeftToRight

Presumably you could loop through all the sheets of interest and run
this code for each.  You'd need to determine the size of your data
range in each sheet (or is it always the same?).  Post back if this is
close to what you were looking for and I'll develop it a bit further.

Rgds,
Andrew

On Feb 17, 1:34=A0pm, avi <avi38...@gmail.com> wrote:
> Hi,
>
> I need to rearrange columns on many sheets in a certain order based on
> on column header.
> For example, my columns might come into my spreadsheet as
> C,B,D,G,A,H,I,F , or as F,B,C,A,D =A0etc.
> I want them all sorted say A,B,C,D - the rest of the columns is
> irrelevant.
>
> How do I accomplish this ?
> TIA

0
Andrew
2/17/2010 1:58:48 PM
Andrew, note that I just want to reorder columns C, A, B into A, B, C
not to sort data in columns.
There is a similar post on this group -> macro "Sub blah()" ; that's
what I want but not on a new sheet but I want to be able to run it
across all the existing sheets.

Antonio
0
avi
2/17/2010 2:09:31 PM
Since i do not know if you have any unique identification of columns, 
I'll assume that in first cell (row 1) there are letters for columns...


Sub MoveandCountColumns()
10 For i = 1 To 254 'As 255 is maximum number of columns

     If Len(Cells(1, i).Value) = 0 Then Exit For 'This is end of columns

     If Columns(Cells(1, i).Value).Column <> i Then
         Columns(Cells(1, i).Value).Select
         Selection.Copy
         Columns(255).Select
         ActiveSheet.Paste

         Columns(i).Select
         Selection.Copy
         Columns(Cells(1, i).Value).Select
         ActiveSheet.Paste

         Columns(255).Select
         Selection.Copy
         Columns(i).Select
         ActiveSheet.Paste
         GoTo 10
     End If
Next

I'm usind column 255 as temporary column for data that should be removed.
I'll try to explain... If in first column you have C and in third you 
have E then i'll copy E column to column 255 then copy first column to 
its right place and then put back column 255 content in first columns...
before macro i had C A E, after i have E X C, what means that i C is in 
right place so i start from begin again until all columns are in right 
places.


Here you will need some loops to identify what column on what place you 
will need.
If you can provide

On 17.02.2010 14:34, avi wrote:
> Hi,
>
> I need to rearrange columns on many sheets in a certain order based on
> on column header.
> For example, my columns might come into my spreadsheet as
> C,B,D,G,A,H,I,F , or as F,B,C,A,D  etc.
> I want them all sorted say A,B,C,D - the rest of the columns is
> irrelevant.
>
> How do I accomplish this ?
> TIA
0
Monarch
2/17/2010 3:53:24 PM
Hi Monarch,

> Since i do not know if you have any unique identification of columns,
> I'll assume that in first cell (row 1) there are letters for columns...

Answer to your query is YES. ROW 1 contains unique identification of
columns.
I want to arrange couple of columns across all the sheets in the same
way since I have them now randomly placed across sheets in different
columns. Namely these are: "NUM", "SYS", "DIA", "TAG" etc...

Your code works perfectly on one sheet where 1st row (as you said) has
letters but can you help me with this.
TIA


0
avi
2/17/2010 5:24:36 PM
Ok, here is solution

Sub MoveandCountColumnsA()
10 For i = 1 To 254 'As 255 is maximum number of columns

     If Len(Cells(1, i).Value) = 0 Then Exit For 'This is end of columns
         col = ColumnPlace(Cells(1, i).Value, i)
     If col <> i Then
         Columns(col).Select
         Selection.Copy
         Columns(255).Select
         ActiveSheet.Paste

         Columns(i).Select
         Selection.Copy
         Columns(col).Select
         ActiveSheet.Paste

         Columns(255).Select
         Selection.Copy
         Columns(i).Select
         ActiveSheet.Paste
         GoTo 10
     End If
Next

End Sub

and ColumnPlace Function. This function determine what is column 
identifier and in which column should it move data.
You can add in CASE what is column header and where you wish it to put 
that column.
Do not chage "Case else" part...


Public Function ColumnPlace(ColumnName, CurrColumn)
Select Case ColumnName
     Case "NUM"
         ColumnPlace = 1
     Case "SYS"
         ColumnPlace = 2
     Case "DIA"
         ColumnPlace = 3
     Case "TAG"
         ColumnPlace = 4
     Case "VAR2"
         ColumnPlace = 5
     Case Else
         ColumnPlace = CurrColumn
End Select
End Function

This code will move every column on its needed place only if that column 
is mentioned in ColumnPlace function

On 17.02.2010 18:24, avi wrote:
> Hi Monarch,

> I want to arrange couple of columns across all the sheets in the same
> way since I have them now randomly placed across sheets in different
> columns. Namely these are: "NUM", "SYS", "DIA", "TAG" etc...
>
> Your code works perfectly on one sheet where 1st row (as you said) has
> letters but can you help me with this.
> TIA
>
>
0
Monarch
2/18/2010 3:48:54 PM
Hi,

While I was waiting on a reply, I modified the code found on
http://www.pcreview.co.uk/forums/thread-2587219.php
in such way that I am pasting copied columns from clipboard by
inserting it to the left of the first column (A).
It also works but I can't manage to run it across all the sheets in
workbook.
Note: there is a limitation in my code (as far I can see) that first
column in all the sheets needs to have the same header. Otherwise, if
the first column is to be pasted on the left of it - there's error. (I
don't have code with me now, but will post it next week when I am back
at work. Basically it is very close to the code on the link above )...
Luckily, all my sheets start with the same header in column A so I am
able to arrange it.

The code you posted ( thanx very much for it ) works perfectly on one
sheet.
However there is also limitation that there shall be no blank column
between columns of interest ie if there is blank on between, say "NUM"
& "SYS" nothing happens.
Also, please note that I wanted to run it across all the sheets in a
workbook.
0
avi
2/18/2010 6:29:40 PM
Well there is also another option as advised by Ax on Dbforums to use
Data|Sort, Options and Under Orientation, select "Sort left to
right".
The only thing needed here is Custom List that defines desired columns
order. (see below OrderCustom:=6)

----------------------
Sub Macro1()
    Cells.Select
    Selection.Sort Key1:=Range("A1"), Order1:=xlAscending,
Header:=xlGuess, _
        OrderCustom:=6, MatchCase:=False, Orientation:=xlLeftToRight,
_
        DataOption1:=xlSortNormal
End Sub
----------------------

If only I could run this for all the sheets, it is then solved...
0
avi
2/18/2010 7:16:53 PM
here is complete solution
Does not stop on blank cell (it stops if there are 3 (userdefined) blank 
cell in a row)
If works on all sheets in a workbook
Custom list can be arranged in ColumnPlace function (just insert new 
case line with whatever content of column and desired place of column

here is code:

Sub MoveandCountColumnsA()

Static CountBlanks
'Next two lines cycle thru worksheets
For Each a In Worksheets
     a.Activate

10     For i = 1 To 254 'As 255 is maximum number of columns

         If Len(Cells(1, i).Value) = 0 Then
             CountBlanks = CountBlanks + 1
'If there is 3 columns in a row that was blank assume last column
             If CountBlanks > 3 Then
'3 blanks in a row, assume we are over last column
                 Exit For
             End If
         Else
'Reset counter if there is only 1 or 2 blank cells
             CountBlanks = 0
         End If
             col = ColumnPlace(Cells(1, i).Value, i)
         If col <> i Then
             Columns(col).Select
             Selection.Copy
             Columns(255).Select
             ActiveSheet.Paste

             Columns(i).Select
             Selection.Copy
             Columns(col).Select
             ActiveSheet.Paste

             Columns(255).Select
             Selection.Copy
             Columns(i).Select
             ActiveSheet.Paste
             GoTo 10
         End If
     Next
Next

End Sub

Public Function ColumnPlace(ColumnName, CurrColumn)
     Select Case ColumnName
         Case "NUM" 'Put here content of first cell of column
             ColumnPlace = 1 'Put here desired place of column
         Case "SYS"
             ColumnPlace = 2
         Case "DIA"
             ColumnPlace = 3
         Case "TAG"
             ColumnPlace = 7
         Case "VAR2"
             ColumnPlace = 5
         Case Else
             ColumnPlace = CurrColumn
     End Select
End Function

And avi, you are welcome, if there is anything you would like me to 
change, just ask :)

On 18.02.2010 19:29, avi wrote:

> Hi,
>
> While I was waiting on a reply, I modified the code found on
> http://www.pcreview.co.uk/forums/thread-2587219.php
> in such way that I am pasting copied columns from clipboard by
> inserting it to the left of the first column (A).
> It also works but I can't manage to run it across all the sheets in
> workbook.
> Note: there is a limitation in my code (as far I can see) that first
> column in all the sheets needs to have the same header. Otherwise, if
> the first column is to be pasted on the left of it - there's error. (I
> don't have code with me now, but will post it next week when I am back
> at work. Basically it is very close to the code on the link above )...
> Luckily, all my sheets start with the same header in column A so I am
> able to arrange it.
>
> The code you posted ( thanx very much for it ) works perfectly on one
> sheet.
> However there is also limitation that there shall be no blank column
> between columns of interest ie if there is blank on between, say "NUM"
> &  "SYS" nothing happens.
> Also, please note that I wanted to run it across all the sheets in a
> workbook.
0
Monarch
2/19/2010 8:57:01 AM
Well, all I can say: Thanx very much Monarch!
Finally I can rearrange it now... :-)
0
avi
2/22/2010 6:44:02 AM
Reply:

Similar Artilces:

More Columns #2
I am using all columns through IV on one of my worksheets. Does anyone know how to get more columns? Hi stacy know way using Excel. this is the maximum! -- Regards Frank Kabel Frankfurt, Germany Stacy Haskins wrote: > I am using all columns through IV on one of my > worksheets. Does anyone know how to get more columns? As Frank said, that's the maximum cols But maybe you could try transposing your table / data ? (Excel has a lot more rows than columns) If so, try: http://tinyurl.com/2nmyy for an example on using TRANSPOSE() For a one-time Tranpose: Copy > Paste Specia...

Looking for Excel Help
I'm a very novice Excel user and am looking for a little help with creating a formula for a spreadsheet I'm creating for my personal use. I would appreciate some assistance if possible. Thanks in advance. Dan --- Message posted from http://www.ExcelForum.com/ Hi Dan! Post a sample of what you want to do. Your question is just a tad open ended <g> -- Regards Norman Harker MVP (Excel) Sydney, Australia njharker@optusnet.com.au Excel and Word Function Lists (Classifications, Syntax and Arguments) available free to good homes. "DanB4105" <DanB4105.ywtpa@excelfor...

New to excel
Hi All, I'm new to Excel ( and to this forum :) ) and so I hope somebody may b able to help me. I've got 2 questions.... QUESTION 1 I've got a spreadsheet which takes data from one worksheet and uses i to calculate data in a second worksheet using the following code formula: =IF('4th November 2005'!B19="","nothing here dude",IF(B19<'4th Novembe 2005'!B19,"UP",IF(B19='4th November 2005'!B19,"Same",IF(B19>'4t November 2005'!B19,"DOWN")))) The problem is, when I create a new worksheet I have...

Excel button problem
Hi All I have a macro that copies a worksheet in the active workbook and puts it into a new workbook - then formats it and deletes any buttons on the worksheet. On the first click on the button the macro works ok. On the second click, it fails because the all assigned macros on all buttons in the active workbook changed from "mba" to "book1!mba". Book 1 doesn't exists (wasn't opened, wasn't saved, doesn't have the macros). I've never experienced this problem before?? Can anyone help to solve this problem? FYI The macro to do this is c...

Excel 97 #9
Please can anyone help??? I have two columns in Excel 97. The first contains a list of statu values eg. pending, or granted or withdrawn. The second contains date eg.01/12/1997, 05/06/2003. I woudl like to know how to get all th granted apps before 31/12/2003. Can anyone help please -- Message posted from http://www.ExcelForum.com theres many ways, but an easiest way would be to do a sort. Highlight the 2 columns, click on data, then sort, then sort by status, then by date. this should group them all together. hope this helps...toe >-----Original Message----- >Please can anyo...

Columns #4
My columns in Excel have disappeared how do I get them back? Hi Me! I'm just guessing what you mean. Use: Tools > Options > General Remove check from "R1C1 reference style" OK -- Regards Norman Harker MVP (Excel) Sydney, Australia njharker@optusnet.com.au Excel and Word Function Lists (Classifications, Syntax and Arguments) available free to good homes. "me" <anonymous@discussions.microsoft.com> wrote in message news:12D9050B-079C-476D-B5B6-84445F60EA51@microsoft.com... > My columns in Excel have disappeared how do I get them back? Another gue...

I need a macro
I would like a macro to do the following: I would place the the cursor in any cell and this macro would give me the average of all the entries to the left if the selected cell. EX: I place the cursor in cell M12. I want this macro on display in cell M12 the average of all the values from Col C12 to Col L12. Note that there may NOT be entries in all the cells in that range. Also the start point would always be col C .Thanks You can do this easily with a worksheet_selection event in the sheet module but you would probably want to restrict to a certain range or columns and rows or it woul...

How do I Remove a Split from my Comments in Excel 2003? #2
I have set my current workbook to split/freeze the first column and first 2 rows. Now, when I add a comment to the second row (in any column) my comments are cut off if I should scroll down. I don't ever remember the behavior before. And I don't know what I've done to enable it but it's really annoying. How do turn this off ? ...

print multiple pages on one sheet of paper
I am using mailmerge in Publisher to create placecards for a party we are hosting. The final size of the placecards is 1.5" by 1.5" and we have to print 100 final cards. Publisher gives me the option of printing multiple copies of the same page on one sheet of letter sized paper or one page on one sheet of letter sized paper. What I would like to do, however, is print multiple different pages on one sheet of paper. If I cannot find a solution for this, I will need to print 100 separate pages with a 1.5" square box of copy in the center of each sheet. In page setup, sel...

learning Excel #3
Hi, I was considering learning Excel as an additional tool for my data analysis work. Is it better to use data sets that I have previously used with SPSS and apply the same analysis tools as in SPSS? For applying the appropriate tools, I was considering using excel's online help. The second option I have is to use some excel book for data analysis and apply the techniques to data sets provided with the book. Any suggestions????? regards Metal ...

unable to paste Excel 2003 chart into Outlook 2003
(This was posted on "excel.charting" group.) I have a user who's unable to paste an Excel 2003 chart into Outlook 2003 email message. In Outlook options, the checkbox is selected for "Use Microsoft Office Word 2003 to edit e-mail messages". When I tested this on my own computer running the same version of Office, if the box is check, I have no problem pasting; if this box is cleared, I cannot paste. But on his computer, it doesn't work regardless. Thanks and regards, TL ...

Excel corrupts when asking to update vlookups
We are experiencing weird behavior with some Office 2K3 Excel spreadsheets that contain lots of calculations, but no macros. On some pc’s Excel acts normally, on others you get the error. I have a couple of screen shots available. Any help is appreciated. If desired, send your file to my address below. I will only look if: 1. You send a copy of this message on an inserted sheet 2. You give me the newsgroup and the subject line 3. You send a clear explanation of what you want 4. You send before/after examples and expected results. -- Don Gu...

Uninstall of mappoint has caused errors with excel
Hi, I am running Office 2003 on the terminal server (windows 2003) and had a copy of mappoint as well. This is a mapping program. We ininstalled mappoint which has caused an error message with Excel and other office products. The error says "Cd:\documents and settings\administrator.ocrdc1\application data\microsoft\addins c:\Program files\common files\microsoft shared\geography\mpoai9.dll is not a valid add-in." I then click OK and excel opens up and everything is fine. The problem is that we are using other programs as well such as Quickbooks that export to excel and t...

Excel VBA
When you select the autofilter, the drop down list is created from the unique data in that column. Is there any way to customize this list, so the changes are permanent? For instance, I might have in one(1) column the following 4 row entries: red, blue, green (all are single cell entries) red, blue red blue, green I want my autofilter drop down list to read: red instead of red, blue, green blue red, blue green red blue, green (like normal) If I chose red from the drop down list...

Problem with named range for a large spreadsheet in Excel 2007
Hello, I am trying to generate a large Excel spreadsheet apprx. 10000 rows and 40 columns. I am generating defined name section in the Workbook.xml part of the XLSM package. Here is a sample entry from that section <definedName name="_._44802_._0_._0_._0_._top_line" localSheetId="0" hidden="1">Sheet1!$B$2</definedName> Although the generation goes fine, I can not open the spreadsheet as the Excel throws an error message saying the package is corrupt. But this is not the case if the spreadsheet is small say, 200 rows by 10 columns. ...

how do I add error bars to a 3D chart in excel?
The help states you can only add error bars to data series in 2D area. Is there a way to add them to a 3D chart? Hi, I would not have thought so. Obviously as it is not a built-in option the only way would be a work around perhaps using dummy series. Unfortunately you can create 3d combination charts. Stick with the 2d view. Cheers Andy elahe wrote: > The help states you can only add error bars to data series in 2D area. Is > there a way to add them to a 3D chart? -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info I checked, and error bars are not offered for 3D ch...

Call & Place Graphic Based on Cell Value?
Is there any way to call & place a graphic image based upon a cell value? Maybe you can look at J.E. McGimpsey's page: http://www.mcgimpsey.com/excel/lookuppics.html documike wrote: > > Is there any way to call & place a graphic image based upon a cell value? -- Dave Peterson ...

q Emailing Excel Sheet With Outlook
I am trying to send a table from Excel within the body of an Outlook (lastest versions) to be sent as a fax. Am able to do this, BUT when the document prints out on the fax machine the formating is off (too big for the sheet). I am flexible on changing the method I send it to the fax machine, however it must be sent to the fax via macro. Below is the code I am using. Any help would be greatly appreciated. David Public Sub DoIt() 'On Error GoTo Handler Dim EmailAddress(0 To 2) As String Dim Count As Integer Dim N As Integer Dim sRec1(0) As String Dim sRec2(0 To 1) As...

I need to print a word in PDF from excel.
Hi, In my excel Macro, I update several values and then open a word linked with that excel. Finally what I need to do is to print that word to PDF. I already have a PDF Printer, so I just need the code to do it. Can anybody help me? Thanks in advance. Gast=F3n. Habilita la impresora predeterminada como la PDF y ya lo puedes imprimir a al formato deseado Gracias Francisco,=20 Tienes alg=FAn codigo para ello? gracias Repitiendo: Desde el panel de impresoras asigno primero la que me interesa y despues ejecuto mi macro desde el archivo excel asignando la instruccion sig: midefaultes = a...

How do I get Excell to sort dates that range from 1800 to 1900's
I have posted a cemetery survey on Excell spreadsheet. When I try to sort the birth dates or death dates in ascending or descending order the range of 1900 dates will sort but the 1800 dates fall after the 1900 and will not sort. Why? Is this inherit with this program? The WinXL default dates start with 31 December 1899, so earlier "dates" are interpreted as Text. You can use helper columns and text functions (LEFT(),RIGHT(),MID()) to put the Year, Month and Day in separate columns, then sort. Take a look here for additional workarounds: http://j-walk.com/ss/excel/files...

Control End After the Sheet is Modified
Hi, I use control end a lot to go to the bottom right corner of my big sheets. If you delete rows & columns of data it no longer goes to the right hand of the data. Is there any easy way to navigate to the end of the current data? End and down arrow doesn't work if there are gaps in the data. Thanks for looking. Paul You should use <Home> <End> Kassie "Paul" wrote: > Hi, > I use control end a lot to go to the bottom right corner of my big sheets. > If you delete rows & columns of data it no longer goes to the right hand of > the data. Is...

How do I lock individuals cells within an Excel spreadsheet so th.
i am trying to lock cells that have formulas in them, but other cells in the spreadsheet need to be unlocked so the end users can enter information. Hi first select the cells for which you want to allow entries and goto 'Format - Cells - Protection' and uncheck 'Locked'. Now protect the sheet 'Tools - Protection' "ucastores" wrote: > i am trying to lock cells that have formulas in them, but other cells in the > spreadsheet need to be unlocked so the end users can enter information. ...

GPS 8 service pack 2 and add new company
After installing service pack 2 for GP 8, I am not able to add or log on to the new company. Error during upgrade is “Entries haven't made to all required fields. Would you like to show the required fields on all windows in greatplains” When I try to log on to GP getting another error “file for this company have not been updated” Please help Rajesh ...

Automatically Add Address to Contacts
This feature was available in OL2000 when you replied to someone. Can this be done in OL2003? -- John Harris (Harry) Computer Troubleshooters - Hornby Christchurch New Zealand No version of Outlook had this feature except Outlook 98/2000 in IMO mode. You'd have to create a feature like this with code: http://www.outlookcode.com/d/code/autoaddrecip.htm -- Russ Valentine [MVP-Outlook] "John Harris" <johnh@antispam.comptroub.co.nz> wrote in message news:ueDWZH8mEHA.592@TK2MSFTNGP11.phx.gbl... > This feature was available in OL2000 when you replied to someone. ...

Any way to open an excel file directly to a worksheet?
I am building an application with an icon that launches an excel file when clicked. Is there any way I can open the file directly to a specified worksheet? The names of the worksheet are fixed and so is the file, so I am guessing adding some parameter after the filename should do the trick. Any help will be appreciated. Regards Sid -- skiddyrow ------------------------------------------------------------------------ skiddyrow's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=23965 View this thread: http://www.excelforum.com/showthread.php?threadid=386335 Hey...