Insert formula with dynamic row

后端 未结 3 1107
旧时难觅i
旧时难觅i 2021-01-25 23:33

I have a formula that looks for a \"Date:\" Value in column A and pastes a formula in the adjacent B cell, but I can\'t figure out how to make the formula dynamic.

So if

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 00:18

    You could read in the .Row property of the cell object and use that in your formula.

    Like so:

    Sub Check()
        Dim rng As Range
        Dim i As Long
        Dim lRow As Long
    
        Set rng = Range("A8:A48")
    
        For Each cell In rng
            'test if cell is empty
            If cell.Value = "Date:" Then
                'write to adjacent cell
    
                lRow = cell.Row 'Get the current row
    
                'Use the lRow variable in the formula to create the formula dynamically
                cell.Offset(0, 1).Formula = "=TEXT(T" & lRow & ",""mmm-dd-yyyy"")&"" | ""&V" & lRow & "&"" - ""&U" & lRow & "&"" | Dept: ""&W" & lRow & ""
    
            End If
        Next
    End Sub
    

    I believe the formula is being set correctly. A quick test showed that it output a valid formula. Let me know if anything needs tweaked.

提交回复
热议问题