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

我有代码循环通过一个工作表上的列表,然后是从相应的数据透视表中select一个项目,这是行不通的。 数据透视表是由我创build的macros创build的,透视表生成得很好。 对于我的生活,虽然我无法弄清楚为什么当我设置数据透视表的CurrentPage部分等于我的variables它不会设置它。 这里是我用来循环的代码:

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 

任何build议将不胜感激

这里有一些重写这些代码的技巧,它更容易遵循,并且不使用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 ActiveSheet.PivotTables("HcahpsPivotTrendTable").PivotFields("Doctor") .CurrentPage = vPhys2 End With