Excel is calculating a formula with a VBA function as an error unless it is re-entered

后端 未结 3 1844
予麋鹿
予麋鹿 2020-12-05 15:37

I\'ve got a simple if statement set up in a worksheet where the if condition is VBA user defined function:

Function CellIsFormula(ByRef rng)
    CellIsFormul         


        
3条回答
  •  萌比男神i
    2020-12-05 16:02

    I think your problems are because the 'HasFormula' Property returns a variant, not a boolean. If the range has mixed formulas and values, HasFormula will return null. Plus your not defining the rng as a Range object, and not specifying output type. I suggest an approach like this. It can be modified to return a boolean pretty easily.

    Public Function CellIsFormula(rng As Range) As String
    
    Application.Volatile
    
        Dim testVal As Variant
    
        testVal = rng.HasFormula 'HasFormula returns variant type
    
        'testval is null if cells are mixed formulas and values
        If IsNull(testVal) Then
            testVal = "Mixed"
        End If
    
        Select Case testVal
            Case True
                CellIsFormula = "All Cells in Range Have formula"
            Case False
                CellIsFormula = "No Cells in Range Have formula"
            Case "Mixed"
                CellIsFormula = "Some Cells in Range Have formula"
            Case Else
                CellIsFormula = "Error"
        End Select
    End Function
    

提交回复
热议问题