Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel column number from column name

Tags:

excel

vba

How to get the column number from column name in Excel using Excel macro?

like image 368
Paritosh Ahuja Avatar asked Apr 11 '12 13:04

Paritosh Ahuja


People also ask

How do I get column numbers in Excel?

The COLUMN function returns the column number of the given cell reference. For example, the formula =COLUMN(D10) returns 4, because column D is the fourth column.

Can you reference column by number Excel?

By default, Excel uses the A1 reference style, which refers to columns as letters (A through IV, for a total of 256 columns), and refers to rows as numbers (1 through 65,536). These letters and numbers are called row and column headings. To refer to a cell, type the column letter followed by the row number.


1 Answers

I think you want this?

Column Name to Column Number

Sub Sample()     ColName = "C"     Debug.Print Range(ColName & 1).Column End Sub 

Edit: Also including the reverse of what you want

Column Number to Column Name

Sub Sample()     ColNo = 3     Debug.Print Split(Cells(, ColNo).Address, "$")(1) End Sub 

FOLLOW UP

Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.

In such a case I would recommend using .FIND See this example below

Option Explicit  Sub Sample()     Dim strSearch As String     Dim aCell As Range      strSearch = "Salary"      Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _     LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _     MatchCase:=False, SearchFormat:=False)      If Not aCell Is Nothing Then         MsgBox "Value Found in Cell " & aCell.Address & _         " and the Cell Column Number is " & aCell.Column     End If End Sub 

SNAPSHOT

enter image description here

like image 149
Siddharth Rout Avatar answered Oct 15 '22 05:10

Siddharth Rout