Excel VBA evaluate formula from another sheet

亡梦爱人 提交于 2020-01-11 13:01:29

问题


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

回答1:


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



回答2:


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



回答3:


I think you are looking for Application.Caller:

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



回答4:


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) ))


来源:https://stackoverflow.com/questions/36825742/excel-vba-evaluate-formula-from-another-sheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!