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

Excel VBA创建数据透视表仅能加载1个值字段其余4个字段获取失败

问题根因

你的代码无法正常添加剩余值字段,是3个核心错误导致的:

  • 重复创建透视表:先通过PCache.CreatePivotTable在PSheet.Cells(2,1)位置创建了名为"PivotTable"的透视表,又重复调用同方法在PSheet.Cells(1,1)位置创建同名透视表,直接触发缓存冲突
  • 字段引用规则错误:通过PivotFields调用字段时,必须传入数据源的原始表头名称,不能使用透视表自动生成的带"Sum of "前缀的显示名;你写的字段名还多了多余的右括号,和原始表头完全不匹配,自然无法识别
  • 方法调用错误:添加透视字段要使用PivotFields属性,你写的.addPivotFields("Sum of Toll)")属于方法误用,语法本身不成立
  • 数据源范围计算错误:原代码从第14行开始取数时,Resize参数未扣除14行以上的空行,会把无效区域纳入数据源范围

修正后可直接运行的代码
Sub Pivot()
    Dim PSheet As Worksheet
    Dim DSheet As Worksheet
    Dim PCache As PivotCache
    Dim PTable As PivotTable
    Dim PRange As Range
    Dim LastRow As Long
    Dim LastCol As Long

    Application.ScreenUpdating = False

    Set PSheet = Worksheets("PivotTable")
    Set DSheet = Worksheets("Options")
    PSheet.Cells.Clear ' 清空原有内容避免重复创建报错

    ' 精准计算数据源范围(表头在第14行)
    LastRow = DSheet.Cells(DSheet.Rows.Count, 1).End(xlUp).Row
    LastCol = DSheet.Cells(14, DSheet.Columns.Count).End(xlToLeft).Column
    Set PRange = DSheet.Cells(14, 1).Resize(LastRow - 13, LastCol)

    ' 仅创建一次透视缓存和透视表
    Set PCache = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=PRange)
    Set PTable = PCache.CreatePivotTable( _
        TableDestination:=PSheet.Cells(2, 1), _
        TableName:="PivotTable")

    ' 添加行字段
    With PTable.PivotFields("Client")
        .Orientation = xlRowField
        .Position = 1
    End With
         
    ' 添加值字段,全部引用数据源原始表头名
    With PTable.PivotFields("Final Base")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 1
        .NumberFormat = "#,##0"
        .Caption = "Sum of Final Base"
    End With

    With PTable.PivotFields("Green")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 2
        .Caption = "Sum of Green"
    End With

    With PTable.PivotFields("Amber")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 3
        .Caption = "Sum of Amber"
    End With

    With PTable.PivotFields("Toll")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 4
        .Caption = "Sum of Toll"
    End With

    With PTable.PivotFields("Red")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 5
        .Caption = "Sum of Red"
    End With

    ' 设置透视表样式
    PTable.ShowTableStyleRowStripes = True
    PTable.TableStyle2 = "PivotStyleMedium9"

    Application.ScreenUpdating = True
End Sub

补充说明
  • 如果你的原始表头中Green/Amber/Toll/Red字段本身带特殊后缀或括号,直接把代码中对应PivotFields("")引号内的内容改成和Options工作表第14行的表头完全一致即可
  • 代码全程直接操作定义好的PTable对象,不依赖ActiveSheet,切换工作表时不会触发报错
  • 值字段通过.Caption属性自定义显示名称,不需要提前引用透视表自动生成的带前缀字段名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 04:09:29