VBA循环通过数据透视表Excel 2007

时间:2014-03-03 19:18:53

标签: excel vba excel-vba

我的代码循环遍历一个工作表上的列表,然后从相应的数据透视表中选择一个项目,这不起作用。数据透视表是由我创建的宏创建的,数据透视表生成得很好。对于我的生活虽然我无法弄清楚为什么当我将数据透视表的CurrentPage部分设置为等于我的变量时,它不会设置它。这是我用来循环的代码:

Sub m4_HCAHPS_Macro()

Dim vPhys2 As String
Dim vrow2 As Long
Dim vlastphys2 As String

vrow2 = 1

nextRow2:

Sheets("hcahps doctors").Activate
Range("A" & CStr(vrow2)).Select

vPhys2 = ActiveCell.Value

If Len(vPhys2) < 1 Then
    MsgBox "All Done Here"
    GoTo subcomplete
End If

Sheets("hcahps").Activate
With ActiveSheet.PivotTables("HcahpsPivotcurrentTable").PivotFields("Doctor").CurrentPage = vPhys2
End With

With ActiveSheet.PivotTables("HcahpsPivotTrendTable").PivotFields("Doctor").CurrentPage = vPhys2
End With

Sheets("hcahps report").Activate

vrow2 = vrow2 + 1
vlastphys2 = vPhys2

GoTo nextRow2

subcomplete:

Exit Sub

End Sub

任何建议都将不胜感激

1 个答案:

答案 0 :(得分:2)

以下是重写此代码的一些提示,以便更容易理解,并且不会使用Activegoto语句的常见缺陷。

Sub m4_HCAHPS_Macro()

    Dim vPhys2 As String
    Dim vrow2 As Long: vrow2 = 1
    Dim vlastphys2 As String

    Dim wksDoctors As Worksheet
    Dim wkshcahps As Worksheet

    Set wkshcahps = Sheets("hcahps")
    Set wksDoctors = Sheets("hcahps doctors")

    vPhys2 = wksDoctors.Range("A" & CStr(vrow2)).Value

    Do While (Len(vPhys2) < 1)
        wkshcahps.PivotTables("HcahpsPivotcurrentTable").PivotFields("Doctor").CurrentPage = vPhys2
        wkshcahps.PivotTables("HcahpsPivotTrendTable").PivotFields("Doctor").CurrentPage = vPhys2

        vrow2 = vrow2 + 1
        vlastphys2 = vPhys2

        vPhys2 = wksDoctors.Range("A" & CStr(vrow2)).Value
    Loop

    MsgBox "All Done Here"
End Sub

正如@simoco所说,你的陈述没有正确设定。您不能在自己的with语句中设置值。如果您想:

,可以在with块中设置它
With ActiveSheet.PivotTables("HcahpsPivotTrendTable").PivotFields("Doctor")
    .CurrentPage = vPhys2
End With