【问题标题】:Excel VBA referencing local sheet nameExcel VBA 引用本地工作表名称
【发布时间】:2018-11-28 06:36:12
【问题描述】:

我有一个 VBA 函数,它可以从 ActiveSheet 的图表中输出趋势线方程。不过,我将此功能用作跨多个工作表的加载项。为了获得要计算的函数,当我第一次打开工作簿时,我按了 CTRL-ALT-F9。当我这样做时,该函数会计算ActiveSheet,因此如果我在多个工作表中使用了该函数,它会计算哪个工作表处于活动状态,而不是函数所在的工作表。 理想情况下,我希望该函数针对该离散实例引用它所在的任何工作表。由于它应该广泛适用于多个工作表,因此我不想调用特定的工作表名称。

当前引用为:ActiveSheet.ChartObjects(1).Chart

我试过Worksheet.ChartObjects(1).Chart,但没有编译。

感谢您的任何帮助/指导。

完整代码:

Function TrendLineValue(x) As Double
    Dim c As Chart
    Dim t As Trendline
    Dim e As String

    ' Get the trend line object for activesheet
    Set c = ActiveSheet.ChartObjects(1).Chart
    Set t = c.SeriesCollection(1).Trendlines(1)

    ' Display Equation
    t.DisplayRSquared = False
    t.DisplayEquation = True

    'Number format for accuracy
    t.DataLabel.NumberFormat = "0.0000E+00"

    ' Get equation
    e = t.DataLabel.Text

    ' Create equation for use in cell
    e = Replace(e, "y =", "")
    e = Replace(e, "x6", "x^6")
    e = Replace(e, "x5", "x^5")
    e = Replace(e, "x4", "x^4")
    e = Replace(e, "x3", "x^3")
    e = Replace(e, "x2", "x^2")
    e = Replace(e, "x", " * " & x & " ")

    ' Evaluate
    TrendLineValue = Evaluate(e)
End Function

【问题讨论】:

  • Don't use ActiveSheet。请参阅特定的工作表,使用循环 (For each ws in ThisWorkbook.Worksheets // ws.ChartObjects(1).Chart ...do whatever... // end With) 或仅使用 Worksheets("SheetName").ChartObjects()...。没有minimal reproducible example,很难更具体。
  • BruceWayne 谢谢,但我认为这两种方法都不理想。理想情况下,我只想在单元格中输入函数并让它计算该特定工作表中图表的值。我将更新帖子以包含完整的代码。

标签: excel vba


【解决方案1】:

听起来你可以使用Application.Caller。由于这是在单元格中输入的自定义函数,Application.Caller 返回“指定该单元格的 Range 对象”。那个Range 的Parent 是有问题的工作表。

改变

Set c = ActiveSheet.ChartObjects(1).Chart

到

Set c = Application.Caller.Parent.ChartObjects(1).Chart

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多