2013-12-12 113 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

對不起,上面的最後評論是隱藏的,所以沒有看到它已被解決。 –

相關問題