You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel宏:调试时图表生成在工作表末尾,按钮触发位置异常

解决图表工作表生成位置异常的问题

问题出在未明确限定工作簿对象和使用过时的工作表计数上,以下是修正后的代码和关键说明:

修正后的完整代码

Sub CreateCharts()
    Call BaseFunctions

    If Not YesNoMessageBox() Then
       Exit Sub
    End If

    Const FIRST_ROW As Integer = 3
    Const LAST_ROW As Integer = 32
    
    Dim wb As Workbook
    Set wb = ThisWorkbook
    Dim ws As Worksheet
    Set ws = wb.Worksheets("Year")
    
    Dim i As Integer
    For i = FIRST_ROW To LAST_ROW
        Dim nameCell As String
        nameCell = Trim(ws.Cells(i, 3))
        If nameCell = "" Then
            Exit For
        End If
        
        DeleteWorksheet (nameCell)
        
        Dim newChart As Chart
        ' 明确限定wb.Sheets,使用最新的工作表总数
        Set newChart = wb.Charts.Add2(After:=wb.Sheets(wb.Sheets.Count), NewLayout:=True)
        newChart.ChartType = xlLineMarkers
        ' 明确限定数据源为ws工作表的范围
        newChart.SetSourceData Source:=ws.Range(ws.Cells(i, 4), ws.Cells(i, 19))
        newChart.ChartTitle.Text = nameCell
        newChart.Name = nameCell
        newChart.Axes(xlValue).MinimumScale = 1
        newChart.Axes(xlValue).MaximumScale = 6
        newChart.Axes(xlValue).MajorUnit = 1
        newChart.Axes(xlValue).MinorUnit = 0.1
        newChart.SetElement (msoElementPrimaryValueGridLinesMinorMajor)
        newChart.SetElement (msoElementPrimaryCategoryGridLinesMajor)
        
    Next i
End Sub

关键修改点

  1. 明确限定工作簿对象:所有Sheets引用都加上wb.前缀,避免从按钮触发时,代码默认使用当前活动工作表的上下文,导致计数和位置判断错误;
  2. 限定数据源范围:把Range(...)改为ws.Range(...),确保数据源指向指定的Year工作表,避免因活动工作表变化引发的错误;
  3. 实时获取工作表总数:移除提前定义的count变量,直接用wb.Sheets.Count获取最新的工作表数量,保证每次创建图表时都能定位到最后一个工作表之后。

如果之前尝试移动图表的方案,也可以替换为以下代码(放在Next i前):

newChart.Move After:=wb.Sheets(wb.Sheets.Count)

同样要确保所有引用都限定到wb,避免索引越界或崩溃问题。

内容的提问来源于stack exchange,提问作者Bainion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 09:34:52