我想在一系列单元格中使用公式,但我在该单元格中得到公式,而不是公式的结果。
我尝试了几种不同的方式。
我尝试的第一个脚本在列中一直输入公式,直到最后一行值: -
Dim LastRow As Long
LastRow = Cells(Rows.Count, 5).End(xlUp).Row
Range("DO22:DO" & LastRow).Formula = "IF=COUNTIF(AS22:AU" & LastRow & " ,""=Major Variance"")>0,""Major Variance"",IF(COUNTIF(AS22:AU" & LastRow & " ,""=Minor Variance"")>0,""Minor Variance"",""On Track""))"
这是我尝试过的另一个脚本,但这只是将公式放在范围的第一行: -
Dim LastRow As Long
Dim Rng As Range
Range("DO22:DO" & LastRow).Select
For Each Rng In Range("DO22:DO" & LastRow)
ActiveCell.Formula = "IF=COUNTIF(AS22:AU" & LastRow & " ,""=Major Variance"")>0,""Major Variance"",IF(COUNTIF(AS22:AU" & LastRow & " ,""=Minor Variance"")>0,""Minor Variance"",""On Track""))"
Next Rng
编辑1
我根据某人的回答对代码进行了更改,但我现在收到运行时错误'应用程序定义或对象定义错误。
只有当我在If前添加extra =时才会发生这种情况。该错误出现在
行上Rng.Formula = "=IF=COUNTIF(AS22:AU" & LastRow & " ,""=Major Variance"")>0,""Major Variance"",IF(COUNTIF(AS22:AU" & LastRow & " ,""=Minor Variance"")>0,""Minor Variance"",""On Track""))"
以下是编辑过的脚本: -
Dim Rng As Range
Dim LastRow As Long
LastRow = Cells(Rows.Count, 5).End(xlUp).Row
Range("DO22:DO" & LastRow).Select
For Each Rng In Range("DO22:DO" & LastRow).Cells
Rng.Formula = "=IF=COUNTIF(AS22:AU" & LastRow & " ,""=Major Variance"")>0,""Major Variance"",IF(COUNTIF(AS22:AU" & LastRow & " ,""=Minor Variance"")>0,""Minor Variance"",""On Track""))"
Rng.Value = Rng.Value
Next Rng
答案 0 :(得分:0)
您在第二个中使用activecell,因此如果未选择它,它将仅在活动单元格中。所以你需要改变你的循环
For Each Rng In Range("DO22:DO" & LastRow).cells
然后
rng.Formula = "=IF=COUNTIF(AS22:AU" & LastRow & " ,""=Major Variance"")....
然后
rng.value=rng.value
另外,在第二个中,你没有设置LastRow。
答案 1 :(得分:0)
您的格式错误IF function和COUNTIF function。
'target formula "=IF(COUNTIF(AS22:AU99, "Major Variance"), "Major Variance", =IF(COUNTIF(AS22:AU99, "Minor Variance"), "Minor Variance", "On Track"))
rng.Formula = "=IF(COUNTIF(AS22:AU" & lastRow & ", ""Major Variance""), ""Major Variance"", " & _
"IF(COUNTIF(AS22:AU" & lastRow & ", ""Minor Variance""), ""Minor Variance"", " & _
"""On Track""))"
rng = rng.Value
请注意,如果存在主要差异和次要差异,则主要差异优先。
要将此公式放入每一行并在循环中每次修改该行,代码将如下所示。
Dim lastRow As Long, rng As Range
With Worksheets("Sheet1") '<~~ you should know what worksheet you are on!
lastRow = .Cells(Rows.Count, 5).End(xlUp).Row
For Each rng In .Range("DO22:DO" & lastRow)
rng.Formula = "=IF(COUNTIF(AS" & rng.Row & ":AU" & rng.Row & ", ""Major Variance""), ""Major Variance"", " & _
"IF(COUNTIF(AS" & rng.Row & ":AU" & rng.Row & ", ""Minor Variance""), ""Minor Variance"", " & _
"""On Track""))"
rng.Value = rng.Value
Next rng
End With
但你也可以像这样把公式放到所有的细胞中。
Dim lastRow As Long
With Worksheets("Sheet1") '<~~ you should know what worksheet you are on!
lastRow = .Cells(Rows.Count, 5).End(xlUp).Row
With .Range("DO22:DO" & lastRow)
.Formula = "=IF(COUNTIF(AS22:AU22, ""Major Variance""), ""Major Variance"", " & _
"IF(COUNTIF(AS22:AU22, ""Minor Variance""), ""Minor Variance"", " & _
"""On Track""))"
.Value = .Value
End With
End With