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
Set a variable for the row value and convert it to a string for your formula insert like so
Sub Check()
Dim i As Integer
Dim j As String
'for each row
For i = 8 To 48
If Cells(i, 1).Value = "Date:" Then
'set the string for use in the formula
j = Trim(Str(i))
Cells(i, 2).Formula = "=TEXT(T8,""mmm-dd-yyyy"")& "" | "" &V" & j & "& "" - "" &U" & j & "&"" | Dept: ""&W" & j & ""
End If
Next
End Sub
If your range is really this limited, you would be better of setting a conditional formula directly in your sheet like this:
=IF(A8="Date:",TEXT(T8,"mmm-dd-yyyy") & " | " & V8 & " - " & U8 & " | Dept: " & W8,"")
This will only display the text on the condition that A8 = Date:. Dragging the formula down will increment the row number
Use the R1C1 style of formatting:
Sub Check()
Dim rng As Range
Dim i As Long
Dim cell As Range 'Remember to declare cell as a range.
'Qualify your ranges with at least the sheet name.
Set rng = ThisWorkbook.Worksheets("Sheet1").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"
cell.Offset(0, 1).FormulaR1C1 = "=TEXT(RC20,""mmm-dd-yyyy"")&"" | ""&RC22&"" - ""&RC21&"" | Dept: ""&RC23"
End If
Next
End Sub
RC20
means this row, column 20. R1C20
means row 1, column 20. RC[-1]
means this row, one column to the left.
http://www.numeritas.co.uk/2013/09/the-%E2%80%98dark-art%E2%80%99-of-r1c1-notation/
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.