我是一个绝对的VBA菜鸟,但考虑到我的工作需求不断变化,最近我不得不进入编码领域,因为我们正试图自动完成很多任务。我已经拥有的是以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim pt As PivotTable
Dim pi As PivotItem
Dim strField As String
strField = "Manager"
On Error Resume Next
Application.EnableEvents = False
Application.ScreenUpdating = False
If Target.Address = Range("D1").Address Then
For Each ws In ThisWorkbook.Worksheets
For Each pt In ws.PivotTables
With pt.PageFields(strField)
For Each pi In .PivotItems
If pi.Value = Target.Value Then
.CurrentPage = Target.Value
Exit For
Else
.CurrentPage = "(All)"
End If
Next pi
End With
Next pt
Next ws
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
我正在尝试将其与以下代码结合使用:
Range("AC22:AC60").Copy Range("AF22:AF60")
Range("AL22:Al60").Copy Range("AN22:AN60")
Range("AU22:AU60").Copy Range("AW22:AW60")
但是如果第一个代码中的D1范围发生变化,我只希望复制范围。显然我想自动化而不是将副本编写成宏,所以我请帮助我如何在这里用一块石头杀死两只鸟。
我如何结合这个?
非常感谢,
答案 0 :(得分:0)
如果我理解你的问题,这应该只是伎俩(但我真的不确定我是否完全理解你的问题):
If Target.Address = Range("D1").Address Then
For Each ws In ThisWorkbook.Worksheets
For Each pt In ws.PivotTables
With pt.PageFields(strField)
For Each pi In .PivotItems
If pi.Value = Target.Value Then
.CurrentPage = Target.Value
Exit For
Else
.CurrentPage = "(All)"
End If
Next pi
End With
Next pt
Next ws
Range("AC22:AC60").Copy Range("AF22:AF60")
Range("AL22:Al60").Copy Range("AN22:AN60")
Range("AU22:AU60").Copy Range("AW22:AW60")
End If
如果这不是你需要的,你的意思是这个吗?
If Target.Address = Range("D1").Address Then
For Each ws In ThisWorkbook.Worksheets
For Each pt In ws.PivotTables
With pt.PageFields(strField)
For Each pi In .PivotItems
If pi.Value = Target.Value Then
.CurrentPage = Target.Value
Range("AC22:AC60").Copy Range("AF22:AF60")
Range("AL22:Al60").Copy Range("AN22:AN60")
Range("AU22:AU60").Copy Range("AW22:AW60")
Exit For
Else
.CurrentPage = "(All)"
End If
Next pi
End With
Next pt
Next ws
End If