2013-12-12 115 views
0

有没有办法检查活动单元格的特定公式?这是我运行的一个简单的测试,不断返回“否”。VBA/Excel宏 - 如何检查单元的特定公式

sub Test 

    'Add formula to a Cell 
    Range("J3").Select 
    ActiveCell.FormulaR1C1 = "=R[-1]C+RC[-2]-RC[-1]" 

    If (ActiveCell.Formula = "=R[-1]C+RC[-2]-RC[-1]") Then 
     MsgBox ("Yes") 

    Else 

     MsgBox ("No") 

    End If 
End Sub 

* 更新 * 这是我的工作了。

Sub Test() 

    'Add formula to a Cell 
    Range("J3").Select 
    ActiveCell.FormulaR1C1 = "=R[-1]C+RC[-2]-RC[-1]" 

    'Convert Formula in the Cell to a string 
    Dim strFormula As String 
    strFormula = ActiveCell.FormulaR1C1 


    If (strFormula = "=R[-1]C+RC[-2]-RC[-1]") Then 
     MsgBox ("Yes") 
    Else 
     MsgBox ("No") 
    End If 


End Sub 
+0

您更新的代码没有任何意义。请在我的回答下查看我的评论。 –

+0

当然,你的'.formula'永远不会像'r [] c []'样式。 –

+0

是的,你一直都是对的。我使用.formula代替.formulaR1C1的错误:-) – Ollie

回答

1

这是相当简单的,靠近你提出什么:

If ActiveCell.FormulaR1C1 = "=R[-1]C+RC[-2]+RC[-1]" Then 

'Do Something 

End If 

但是请记住,比较是非常,非常strict-它是区分大小写和空间敏感。

EDIT由于OP的其他问题

根据THIS MSDN LINKRange.FormulaR1C1属性返回Variant类型。在我的情况下,我得到了自动转换,这使得我的代码工作正常。但是,为了避免任何问题,您可以按照以下方式进行转换:

If CStr(ActiveCell.FormulaR1C1) = "=R[-1]C+RC[-2]+RC[-1]" Then 

'Do Something 

End If 
+0

谢谢Kazjaw。它不适合我。我发布了更新到我原来的帖子。 (我是新来的,所以不允许发表评论)。如果可以的话,请看看。非常感谢。 – Ollie

+0

@ user2977498,在'if语句'之前,您可以添加'debug.print activecell.formular1c1'来查看(在IDE的即时窗口中)读取“.formulaR1C1”的方式。你可以在'if语句'中实现它。我想,问题在于你必须在这里做出精确的比较。 –

+0

即时窗口显示为= R [-1] C + RC [-2] -RC [-1] – Ollie

0

我成功运行以下代码。我看不出太大的差别。

Private Sub Try_FormulaAsString() 

Dim testString As String 
testString = Range("J3").FormulaR1C1 

If testString = "=R[-1]C+RC[-2]-RC[-1]" Then 
    MsgBox "Yes" 
Else 
    MsgBox "No" 
End If 

End Sub 

与含公式“= J2 + H3-I3”

我注意到在过去的术语在操作者的差在一些您上述评论, 如-RC [细胞J3 -1]与+ RC [-1]

是否有理由使用.FormulaR1C1而不是.Formula,这将使读取公式更容易,并减少子例程中输入错误的机会?

+0

对不起,上面的最后评论是隐藏的,所以没有看到它已被解决。 –

相关问题