Excel VBA引用本地工作表名称

JDu*_*ale 4 excel vba

我有一个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
Run Code Online (Sandbox Code Playgroud)

Big*_*Ben 7

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

更改

Set c = ActiveSheet.ChartObjects(1).Chart
Run Code Online (Sandbox Code Playgroud)

Set c = Application.Caller.Parent.ChartObjects(1).Chart
Run Code Online (Sandbox Code Playgroud)