评估另一张表中的公式作为当前表

时间:2016-06-16 15:47:26

标签: excel function excel-formula eval

我试图使用Eval()来获取存储在Main上的一些函数,并使用Sheet2中的值对它们进行评估。到目前为止,静态引用Main和纯文本工作,但我在引用相关单元格时遇到了麻烦。

理想情况下,主工作表将静态和相对引用组合在一起,并将列中的函数应用于表中的行(例如,在此示例中为A7,A8,...)。单引号用于形成SQL。这是我试图实现的功能之一。

=CONCATENATE(Main!$B$30, "'", A7, "', '", B7, "', '", C7, "', '", D7, "', '", E7, "', '",F7, "', '",G7, "', '",H7, "', '",I7, "', '",J7, "', '", K7, "', ",$B$4,Main!$B$35)

我认为问题出在我的Eval函数中,它没有将A7评估为活动工作表中的单元格值。我正在研究一种将函数更改为类似CurrentSheet!A7的方法,但无法找到正确的语法。

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

我像这样在Sheet2中引用这个Eval函数,向下复制我的表格列,其中Main!$ E $ 5是一个包含上述excel函数的单元格。

=EVAL(Main!$E$5)

ANSWER

我拿了bwyn的例子并修改了它供我使用。这就是上面的excel函数最终看起来像VB函数。将行号作为参数发送使得调用函数最通用,允许电子表格主控扩展" A"和" K"在一个地方需要的值。

Function EvalInsert(rowNum As Integer)
  Dim shCurrent As Worksheet: Set shCurrent = ActiveSheet
  Dim shMain As Worksheet: Set shMain = Sheets("Main")
  Dim insertClose As String: insertClose = "'));"
  Dim openParen As String: openParen = "'"
  Dim closeParen As String: closeParen = "', "
  Application.Volatile

  Set insertOpen = shMain.Range("B30")
  Set tableId = shMain.Range("B33")
  Set TableName = shCurrent.Range("B1")
  Set insertValues = shCurrent.Range(Cells(rowNum, "A"), Cells(rowNum, "K"))

  EvalInsert = insertOpen.Value

  For Each c In insertValues.Cells
     EvalInsert = EvalInsert & openParen & c.Value & closeParen
  Next

  EvalInsert = EvalInsert & tableId & TableName & insertClose

End Function

我用

打电话给我
=EvalInsert(ROW())

1 个答案:

答案 0 :(得分:1)

在你的连接公式中,似乎只有A7会发生变化。如果是这样,那么您可以按如下方式重写Eval函数:

Function Eval(currShRelRefStr As Range)
   Dim shCurrent As Worksheet, shMain As Worksheet
   Dim mainRng As Range, currShRelRef As Range, currShStaticRef As Range
   Dim aStr As String

   Set shCurrent = ActiveSheet
   Set shMain = Sheets("Main")

   Set mainRng = shMain.Range("B30")
   Set currShRelRef = shCurrent.Range(currShRelRefStr.Value)
   Set currShStaticRef = shCurrent.Range("B3")
   aStr = "a string"

   Eval = mainRng.Value & aStr & currShRelRef.Value & currShStaticRef.Value

End Function