简体   繁体   中英

Excel VBA evaluate formula from another sheet

Solved: The problem is in my formula where I'm referencing a cell using INDIRECT() which doesn't work when sheet is different. See answer.

I have a formula in one sheet and what I want to do is to use the formula from another sheet, using eval to evaluate the formula. However, the result is not as intended. It seems like the formula is using values at Sheet A instead of the caller Sheet B.

Formula in sheet A (See: Screenshot Sheet A )

=IF(ISERROR(INDEX('1516Activity'!$B:$B,MATCH(INDIRECT(ADDRESS(ROW(),COLUMN(D:D) )),'1516Activity'!$C:$C,0))),"-",IF(LEFT(INDEX('1516Activity'!$F:$F,MATCH(INDIRECT(ADDRESS(ROW(),COLUMN(D:D) )),'1516Activity'!$C:$C,0)))="0","N","Y"))

Usage in Sheet B (See: Screenshot Sheet B )

=Eval('CODE-VARS'!$G$5)

VBA:

Function Eval(Ref As String)
    Application.Volatile
    Eval = Application.ThisCell.Parent.Evaluate(Ref)
End Function

You are evaluating the String 'CODE-VARS'!$G$5 which would return the value in that cell not its formula. Try this:

Function Eval(Ref As RAnge)
    Application.Volatile
    Eval = Application.ThisCell.Parent.Evaluate(Ref.formula)
End Function

It seems to me that it references values in whatever sheet is active.

In your Eval function, ensure the target sheet is active:

Function Eval(Ref As String)
    Dim shCurrent As Worksheet: Set shCurrent = ActiveSheet
    Application.Volatile
    Application.ThisCell.Parent.Activate
    Eval = Application.ThisCell.Parent.Evaluate(Ref)
    shCurrent.Activate
End Function

I think you are looking for Application.Caller:

Function Eval(Ref As String)
    Application.Volatile
    Eval = Application.Caller.Parent.Evaluate(Ref)
End Function

The problem is I'm referencing a cell using INDIRECT() which doesn't work when the eval() is called from a different sheet.

This works:

INDEX(D:D,ROW())

This doesn't:

INDIRECT(ADDRESS(ROW(),COLUMN(D:D) ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM