I\'m currently working on a data set which is formatted as a table, with headers. What I need to do is cycle through all cells in a specific column and change the contents.
You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:
Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
cl.Value = "PHEV"
Next cl
The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.
Use this to find the location of any column in a table by its column name:
Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column
This returns the numeric position of a column in the table.
I came across the same problem but no forum could help me, after some minutes I came out with an idea:
match(ColumnHeader,Table1[#Headers],0)
This will return you the number.
If you know the header name, you can find the column based on that:
Option Explicit
Public Sub changeData()
Application.ScreenUpdating = False ' faster for modifying values on sheet
Dim header As String
Dim numRows As Long
Dim col As Long
Dim c As Excel.Range
header = "this one" ' header name to find
Set c = ActiveSheet.Range("1:1").Find(header, LookIn:=xlValues)
If Not c Is Nothing Then
col = c.Column
Else
' can't work with it
Exit Sub
End If
numRows = 50 ' (whatever this is in your code)
With ActiveSheet
.Range(.Cells(2, col), .Cells(numRows, col)).Value = "PHEV"
End With
Application.ScreenUpdating = True ' reset
End Sub