如何有条件地从一个范围向我的数据透视表添加值?

时间:2017-04-03 17:05:10

标签: excel-vba vba excel

我希望能够根据字段的名称更新数据透视表的值字段。例如,我将Fields命名为"添加我","添加我","添加我"," column1",& #34; column2"和" column3"。我基本上需要循环遍历这些字段,并添加"添加我","添加我","添加我",但忽略" column1"," column2"和#34;第3栏和第34条。

我一直试图通过在工作表中指定范围,循环并依赖于值来尝试将其添加为值。

Sub check_data_columns()

Dim c As Range
Dim pvt As PivotTable

For Each c In Range("data_input_columns")

    If Left(c, 6) <> "Column" Then
        Debug.Print "OK column:" & c.Value
        ActiveSheet.PivotTables("pivot_by_week").AddDataField ActiveSheet.PivotTables("pivot_by_week").PivotFields(c), "sum of " & c, xlSum

    Else
        Debug.Print "nothing in column: " & c.Value
    End If

Next

End Sub

我每次都会收到1004错误。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我怀疑您的命名范围Range("data_input_columns")不仅包含标题行,还包含其下方数据的行。

因此,当您循环For Each c In Range("data_input_columns")并使用数据到达第二行时,您会收到错误。

我使用For Each C In Range("data_input_columns").Rows(1).Cells仅遍历第一行,您最有可能保留标题行,这些是您要与<> "Column"进行比较的值。

<强>代码

Option Explicit

Sub check_data_columns()

Dim C As Range
Dim pvt As PivotTable

' set the Pivot Table, will have a shorter cleaner code
' avoid using ActiveSheet, try to use fully qualified object, such as Worksheets("Sheet1")
Set pvt = ActiveSheet.PivotTables("pivot_by_week")

For Each C In Range("data_input_columns").Rows(1).Cells ' loop through first row (header row)
    If Not UCase(C.Value) Like "COLUMN*" Then '<-- just in case you have small or capital letters
        Debug.Print "OK column:" & C.Value
        pvt.AddDataField pvt.PivotFields(C.Value), "sum of " & C.Value, xlSum
    Else
        Debug.Print "nothing in column: " & C.Value
    End If
Next

End Sub