Looping through all rows in a table column, Excel-VBA

前端 未结 9 563
予麋鹿
予麋鹿 2020-12-14 19:12

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.

相关标签:
9条回答
  • 2020-12-14 20:08

    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.

    0 讨论(0)
  • 2020-12-14 20:09

    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.

    0 讨论(0)
  • 2020-12-14 20:11

    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
    
    0 讨论(0)
提交回复
热议问题