将另一个 Sheet 的公式计算为当前 Sheet

Evaluate Formula From Another Sheet as Current Sheet

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

理想情况下,主要工作sheet 结合了静态和相对引用,并将函数沿列向下应用到 table 中的行(例如在本例中为 A7、A8... ).单引号用于形成 SQL。这是我要实现的功能之一。

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

我认为问题出在我的 Eval 函数中,它没有将 A7 计算为活动 sheet 中的单元格值。我正在寻找一种方法将函数更改为 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 函数,复制了我的 table 列,其中 Main!$E$5 是一个包含上述 excel 函数的单元格。

=EVAL(Main!$E)

回答

我借鉴了 bwyn 的示例并对其进行了修改以供我使用。这就是上面的 excel 函数最终看起来像 VB 函数的样子。发送行号作为参数使调用函数最通用,允许 spreadsheet master 在一个位置根据需要扩展 "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())

在您的连接公式中,似乎只有 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