简体   繁体   中英

Excel - Rename cell if row contains certain value

I've seen some similar questions but can't quite find an answer for my situation. If data is found in a row, then Column C of that row will be labeled with that data. But I also want all columns below this row to contain this same label in Column C. Until the next data is found, then I want to repeat the same process for the whole document until every row had data in Column C reflecting the data from its particular section.

I probably did a poor job of explaining that, so here is what I would like to happen. Any help would be greatly appreciated.

[Example of what I want the outcome to be.]

This is very simple with just IF formula. Here is the pseudocode:

if the sentence start with "class" then 
  refer to cell next to him
else:
  refer to cell on top of him

公式视图

Which in code look like:

Sub test()
    Dim rng As Range
    With ActiveSheet
        For Each rng In Intersect(.Columns("C"), .UsedRange)
            If Left$(Trim(rng.Offset(, 1)), 5) = "Class" Then
                rng = rng.Offset(, 1)
            Else
                rng = rng.Offset(-1)
            End If
        Next rng
    End With
End Sub

If you were to use column D to determine the last row to loop to you might use the following (swop the "D" for a different column letter if you want to use a different column to determine how far to loop to get to last row)

Option Explicit

Sub test()
    Dim rng As Range
    With ActiveSheet
        For Each rng In .Range(.Cells(1, "C"), .Cells(.Cells(.Rows.Count, "D").End(xlUp).row, "C"))
            If Left$(Trim(rng.Offset(, 1)), 5) = "Class" Then
                rng = rng.Offset(, 1)
            Else
                rng = rng.Offset(-1)
            End If
        Next rng
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM