VBA Excel: Rename columns for easy referencing
-
26-06-2021 - |
Question
I am writing a script that transfers data from Excel cells to different word tables. So far, I am doing it like that:
wordDoc.Bookmarks("Editor").Range.Text = Sheets("Product Eval").Range("E" & evalRow).Text
where evalRow is computed before.
Now, I want to avoid that I have to rewrite the whole code when someone adds a column before column E. Is it possible to rename whole columns, that they keep their name even if they are moved and that I can reference a specific cell with that column name in VBA?
Solution
Solved this problem by myself:
- mark whole column
- write the desired name in the "Name Box" in the left upper corner of Excel 2007 and press Enter
In VBA, the following code adresses the 4th row in the specific column (I named my column "Employees", according to the title of the column):
test = Sheets("Sheet1").Range("Employees").Cells(4, 1).Text
Note that when working with columns, the second parameter of Cells always has to be 1 (otherwise you leave your column)
OTHER TIPS
Yes. To name a range you should
- select the range in excel
- click the Name box and put in the name you want to put there.
- Now in formulas you can access the cell/range by the name you defined.