不在工作表上运行宏
Posted
技术标签:
【中文标题】不在工作表上运行宏【英文标题】:Run a Macro without being on the sheet 【发布时间】:2022-01-23 19:24:35 【问题描述】:我正在尝试在不同的工作表上激活宏。我编写了一个宏,以便当我从下拉列表中选择一个选项时,它会更新另一张表上的数据透视过滤器字段。问题是我必须在活动表上才能工作。如果有人可以帮忙,我有以下代码,谢谢
Sub FilterPageValue()
Dim pvFld As PivotField
Dim strFilter As String
Set pvFld = ActiveSheet.PivotTables("PivotTable3").PivotFields("Reporting entity")
strFilter = ActiveWorkbook.Sheets("Sheet1").Range("b2").Value
pvFld.CurrentPage = strFilter
End Sub
【问题讨论】:
将Activesheet
更改为sheets("sheet name")
嗨,试过了,但它说'下标超出范围,谢谢'
您确定您在尝试时使用了正确的工作表名称吗?
嗨,是的,它以前工作过,但必须在活动工作表上,当我尝试从另一个工作表运行它时出现错误,谢谢
你把代码中的“sheet name”改成实际的sheet name了吗?
【参考方案1】:
通过下拉过滤数据透视表
您必须在两个代码中调整包含数据透视表的工作表的名称(我选择了Sheet2
)。
标准模块,例如Module1
Option Explicit
Sub FilterPageValue()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Worksheet with cell 'B2'.
Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1")
' Worksheet with 'PivotTable3'.
Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet2") ' adjust! this
Dim pvFld As PivotField
Set pvFld = dws.PivotTables("PivotTable3").PivotFields("Reporting entity")
Dim strFilter As String
strFilter = sws.Range("B2").Value
pvFld.CurrentPage = strFilter
End Sub
表格模块Sheet1
B2
中的值时,此代码将自动运行 Sheet1
(下拉菜单)。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Range("B2"), Target) Is Nothing Then
' Worksheet with 'PivotTable3': adjust!
Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets("Sheet2")
Dim pvFld As PivotField
Set pvFld = dws.PivotTables("PivotTable3").PivotFields("Reporting entity")
Dim strFilter As String
strFilter = Target.Value
pvFld.CurrentPage = strFilter
End If
End Sub
跟进
您可以将代码重写为带有参数的子代码,以便轻松地为多个数据透视表运行代码。表格模块Sheet1
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Range("B2"), Target) Is Nothing Then
Dim pFilter As String: pFilter = Target.Value
UpdateCurrentPage "Sheet2", "PivotTable3", "Reporting entity", pFilter
UpdateCurrentPage "Sheet3", "PivotTable3", "Reporting entity", pFilter
End If
End Sub
Sub UpdateCurrentPage( _
ByVal WorksheetName As String, _
ByVal PivotTableName As String, _
ByVal PivotFieldName As String, _
ByVal PivotPage As String)
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(WorksheetName)
Dim pTable As PivotTable: Set pTable = ws.PivotTables(PivotTableName)
Dim pField As PivotField: Set pField = pTable.PivotFields(PivotFieldName)
pField.CurrentPage = PivotPage
End Sub
【讨论】:
如何将另一个数据透视表添加到代码的另一张表中?谢谢 我添加了另一个版本。 太好了,再次感谢以上是关于不在工作表上运行宏的主要内容,如果未能解决你的问题,请参考以下文章