[英]VBA Loop Through Pivot Table Excel 2007
我的代碼循環遍歷一個工作表上的列表,然后從相應的數據透視表中選擇一個項目,該項目不起作用。 數據透視表由我創建的宏創建,數據透視表生成得很好。 雖然我一生都無法弄清楚為什么將透視表的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
任何建議將不勝感激
這里有一些技巧,可以更輕松地重寫此代碼,並且不使用Active
和goto
語句的常見陷阱。
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塊中進行如下設置:
With ActiveSheet.PivotTables("HcahpsPivotTrendTable").PivotFields("Doctor")
.CurrentPage = vPhys2
End With
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.