Excel 从另一个子系统调用方法时出现无效参数错误

Excel 从另一个子系统调用方法时出现无效参数错误,excel,vba,excel-charts,trendline,Excel,Vba,Excel Charts,Trendline,我有下面的代码从一些工作表中创建图表,并将图表放在它们自己的工作表中。当我自己运行宏时,它工作得非常好。当我从另一个宏中使用调用InsertDNCCharts时,我从带有tl的块中的中得到.Period=7上的“无效参数”错误。为什么会有区别?如果代码自己运行,那么当从另一个子系统调用时,它不应该以相同的方式运行吗 Sub InsertDNCCharts() Dim ws As Worksheet Dim cws As Worksheet Dim country As String Dim l

我有下面的代码从一些工作表中创建图表,并将图表放在它们自己的工作表中。当我自己运行宏时,它工作得非常好。当我从另一个宏中使用
调用InsertDNCCharts
时,我从带有tl的
块中的
中得到
.Period=7
上的“无效参数”错误。为什么会有区别?如果代码自己运行,那么当从另一个子系统调用时,它不应该以相同的方式运行吗

Sub InsertDNCCharts()

Dim ws As Worksheet
Dim cws As Worksheet
Dim country As String
Dim lastrow As Long
Dim chrt As Shape
Dim chrtname As String
Dim xvalues As Range
Dim yvalues As Range
Dim tl As Trendline

For Each ws In ThisWorkbook.Worksheets

    If Right(ws.Name, 6) = "_Chart" Then
        country = Left(ws.Name, Len(ws.Name) - 6)
        Set cws = ThisWorkbook.Worksheets(country)

        lastrow = cws.Cells(Rows.count, "c").End(xlUp).Row
        Set xvalues = cws.Range("c5:c" & lastrow)
        Set yvalues = cws.Range("l5:l" & lastrow)

        cws.Activate
        Application.Union(xvalues, yvalues).Select
        Set chrt = cws.Shapes.AddChart2(201, xlColumnClustered, Cells(5, 2).Left, Cells(5, 2).Top, 1000, 420)

        chrt.Name = ws.Name
        chrtname = chrt.Name
        cws.Cells(5, 1).Select

        With chrt.Chart
            .Location Where:=xlLocationAsObject, Name:=ws.Name
            .Axes(xlCategory).HasMajorGridlines = True
            .Axes(xlCategory).HasMinorGridlines = False
            .Axes(xlValue).HasMajorGridlines = True
            .Axes(xlValue).HasMinorGridlines = False
            .HasLegend = False
        End With

        ws.ChartObjects(chrtname).Activate
        ActiveChart.ChartWizard Title:=country & " Daily New Cases (DNC)"

        Set tl = ws.ChartObjects(chrtname).Chart.SeriesCollection(1).Trendlines.Add

        With tl
            .Type = xlMovingAvg
            .Period = 7                '*******Error on this line. Debug says period=2, which is the default moving average period.
            .DisplayEquation = False
            .DisplayRSquared = False
            .Format.Line.DashStyle = msoLineSysDot
            .Format.Line.Weight = 3.5
            .Format.Line.ForeColor.RGB = RGB(255, 0, 0)
            .Format.Line.Style = msoLineSingle
        End With
    End If
Next ws
End Sub

如果讨论中的图表(创建的图表)至少有7点,则代码可能未引用相应的图表,或者图表未按需要创建


为了检查这一点,我建议您在tl的
行上放置一个断点,并目视检查活动图表是否是您需要的图表,以及它是否符合预期。看起来问题必须在引发错误的行之前出现。

是同一工作簿的模块中的“另一个子”吗?是。它实际上在同一个模块中。如果您在tl的
行上放置一个断点,在处理的第一张工作表上,您是否看到图表已经创建,它看起来是否像假设的那样?我的意思是,创建的图表是否有多个大于或等于7的数据点?因此,在为图表选择我的dat之前,我添加了一个检查,以确保表上没有其他图表对象,它似乎起到了作用。问题不再是复制了<代码>如果ws.ChartObjects.count为0,则对于ws.ChartObjects i中的每个i。删除下一个i End如果
欢迎您回答并获得积分。