Addressing column header name in FOR EACH loop

dotsent

Board Regular
Joined
Feb 28, 2016
Messages
89
Office Version
  1. 365
Platform
  1. Windows
Hi, this seems a simple question, but just can't crack it. Have used plenty of FOR EACH loop within ListObjects in similar ways as the code below. However now come across a real legacy system with obscene amount of columns, making me want to address columns over header names instead of column sequence numbers while running IF-clause. E.g. instead of lstrw.Range(20), I'd like to address it by header name, like lstrw.Range(["Date"]) and not have to keep counting and mapping the columns through numbers. I guess the code would also be more bulletproof against column sequence changes and have better readability.

Have tried different iterations and no suitable leads googling.
VBA Code:
lstrw.Range(["Date"])
gives error message:

Invalid procedure call or argument

VBA Code:
Dim MyTable As ListObject
Dim lstrw As ListRow

Set MyTable = ActiveSheet.ListObjects("Data")
For Each lstrw In MyTable.ListRows
    If lstrw.Range(1) = "A" Then
            lstrw.Range(2) = "B"
    End If
Next lstrw
 

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.
Hi,

give following a try & see if helps

VBA Code:
Dim MyTable As ListObject
Set MyTable = ActiveSheet.ListObjects("Data")

MsgBox ActiveSheet.Range(MyTable.Name & "[Date]").Column

'or another way maybe

MsgBox MyTable.ListColumns("Date").Index

hopefully, either will return the column number

Dave
 
Upvote 0
Solution

Forum statistics

Threads
1,223,893
Messages
6,175,240
Members
452,621
Latest member
Laura_PinksBTHFT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top