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

前端 未结 9 624
予麋鹿
予麋鹿 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: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
    

提交回复
热议问题