简体   繁体   English

Excel VBA评估另一张纸上的公式

[英]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. 已解决:问题出在我的公式中,其中我使用INDIRECT()引用单元格,当工作表不同时,该单元格不起作用。 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. 我在一张纸上有一个公式,而我想做的是使用另一张纸上的公式,并使用eval评估公式。 However, the result is not as intended. 但是,结果不符合预期。 It seems like the formula is using values at Sheet A instead of the caller Sheet B. 似乎公式使用工作表A而不是调用方工作表B的值。

Formula in sheet A (See: Screenshot Sheet A ) 表格A中的公式(请参阅: 截图表格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 ) 表格B中的用法(请参阅: 截图表格B

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

VBA: 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. 您正在评估字符串'CODE-VARS'!$G$5 ,它将返回该单元格中的值而不是其公式。 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: Eval函数中,确保目标工作表处于活动状态:

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: 我认为您正在寻找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. 问题是我使用INDIRECT()引用一个单元格,当从另一张纸上调用eval()时,该单元格不起作用。

This works: 这有效:

INDEX(D:D,ROW())

This doesn't: 这不是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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