我有一个公式在 A 列中查找“日期:”值并将公式粘贴到相邻的 B 单元格中,但我不知道如何使公式动态化。
因此,如果我在 A6 和 A8 中有一个值 - 我希望插入的公式具有相同的行号 T6 和 T8。现在它每次都使用相同的行号。
Sub Check()
Dim rng As Range
Dim i 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
cell.Offset(0, 1).Formula = "=TEXT(T8,""mmm-dd-yyyy"")&"" | ""&V8&"" - ""&U8&"" | Dept: ""&W8"
End If
Next
End Sub
最佳答案
您可以阅读 .Row
cell
的属性(property)对象并在您的公式中使用它。
像这样:
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
我相信公式设置正确。快速测试表明它输出了一个有效的公式。让我知道是否需要调整。
关于vba - 插入具有动态行的公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35989817/